java发送邮件(javaMail通过SMTP发送邮件)

java发送邮件一般使用在注册账号时、或其他通知信息时,网站会使用邮件定时发送、或触发发送邮件通知用户;

1、我是用的是maven开发,所以需要在pom文件中定义jar包:


        javax.mail
        mail
        1.5.0-b01
        
当时jar包放进去却在报错,我以为是这个jar有问题,结果一看是缺少配套的jar包:activation-1.1.jar;

这个jar包还找了好久,地址:http://grepcode.com/snapshot/repo1.maven.org/maven2/javax.activation/activation/1.1

2、需要配置properties文件放置邮箱的smtp服务器地址和端口,以及你要使用的发送的邮箱;

这里面还需要说一下不同的邮件服务器地址和端口可能不一样,请参考:http://blog.csdn.net/ghjzzhg/article/details/77838880

mail.smtp.host=smtp.163.com
mail.smtp.port=25
[email protected]
password=password
java发送邮件(javaMail通过SMTP发送邮件)_第1张图片
3、下面就是代码的部分了, 在你想要调用的方法中定义 send_email();方法

	public static void send_email() throws Exception{
		//你想要发送的邮箱,可以动态加载
	        String to = "[email protected]";
	        String subject = "java邮件";//邮件主题
	        String content = "这是你的java邮件";//邮件内容
	        Properties properties = new Properties();
	        InputStream resourceAsStream = null;
	        try {
	            //此处EmployeeAction为你的当前类
	            resourceAsStream = EmployeeAction.class.getClassLoader().getResourceAsStream("/mail.properties");
//	            resourceAsStream = Object.class.getResourceAsStream("/mail.properties");
	            properties.load(resourceAsStream);
	        } finally{
	            if (resourceAsStream!=null) {
	                resourceAsStream.close();
	            }
	        }
	        System.err.println("properties:"+properties);
	        properties.put("mail.smtp.host", properties.get("mail.smtp.host"));
	        properties.put("mail.smtp.port", properties.get("mail.smtp.port"));
	        properties.put("mail.smtp.auth", "true");
	        Authenticator authenticator = new EmailAuthenticator(properties.get("userName").toString(), properties.get("password").toString());
	        javax.mail.Session sendMailSession = javax.mail.Session.getDefaultInstance(properties, authenticator);
	        MimeMessage mailMessage = new MimeMessage(sendMailSession);
	        mailMessage.setFrom(new InternetAddress(properties.get("userName").toString()));
	        // Message.RecipientType.TO属性表示接收者的类型为TO
	        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
	        mailMessage.setSubject(subject, "UTF-8");
	        mailMessage.setSentDate(new Date());
	        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
	        Multipart mainPart = new MimeMultipart();
	        // 创建一个包含HTML内容的MimeBodyPart
	        BodyPart html = new MimeBodyPart();
	        html.setContent(content.trim(), "text/html; charset=utf-8");
	        mainPart.addBodyPart(html);
	        mailMessage.setContent(mainPart);
	        Transport.send(mailMessage);
	}
4、运行后就可以发送并接受到邮件了,仅供参考~~

也可参考博客:http://blog.csdn.net/adeyi/article/details/19421951
或者:http://www.cnblogs.com/codeplus/archive/2011/10/30/2229391.html


 
  
 
  
 
  
 
 

你可能感兴趣的:(后台方法)