使用java实现发送邮件的功能


首先要在maven添加javamail支持


<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
不加的话会报javax.mail.MessagingException异常
代码如下  :

 1 package com.learn.util;

 /**
* Created by Wangqingyu on 2017/6/3.
*/ import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties; public class SendEmailUtil { //获取用于发送邮件的Session
public static Session getSession() throws MessagingException {
//创建连接对象 连接到邮件服务器
Properties props = new Properties(); //设置发送邮件的基本参数
//发送邮件服务器
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.store.protocol" , "smtp");//设置协议
//发送端口
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true"); Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("邮件发自的邮箱@163.com","邮件发自的邮箱授权码");
}
};
Session session = Session.getDefaultInstance(props, authenticator);
return session;
} //发送邮件,String email为邮件的目标邮箱
public static void send(String email, String sb) throws MessagingException{
Session session = getSession(); try {
Message msg = new MimeMessage(session);
//设置message属性
msg.setFrom(new InternetAddress("邮件发自的邮箱@163.com"));
//InternetAddress[] addrs = {new InternetAddress(email)};
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
msg.setSubject("贵宾xxx先生");//邮箱标题
msg.setSentDate(new Date());//邮箱时间
msg.setContent(sb, "text/html;charset=utf-8");//邮箱内容和格式
//必须为text/html;格式,纯文本格式会被当做垃圾邮件 //开始发送
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} }
}

注意的点:上文中提到的邮箱授权码而不是密码,是因为邮件的发自邮箱需要设置POP3/SMTP/IMAP服务,否则会报503异常
具体如何设置可自行百度。




上一篇:【干货】利用MVC5+EF6搭建博客系统(二)测试添加数据、集成Autofac依赖注入


下一篇:第一次在手机上跑动ane