Java发送邮件
需求:将本地文件以邮件附件形式发送给指定收件人
在项目中需要记录一个排行榜信息给统计人员看,将每月筛选和统计的过程交给代码来实现
使用的发送方是qq邮箱,别的还没试过,接收方126和163都用了
注意,qq邮箱在你每一次更改独立密码或者更改qq密码时会造成授权码失效,所以每次更改完密码后记得更新代码或配置文件中的授权码
上代码:
1.最终发送的方法,参数id不是必须的,是我自定义的方法中用到的
/**
* 发送邮件
*/
public void sendEmail(String id) throws GeneralSecurityException, MessagingException, IOException, SQLException {
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.qq.com"); //设置QQ邮件服务器
prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议
prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码
// QQ邮箱设置SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//1、创建定义整个应用程序所需的环境信息的 Session 对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//传入发件人的姓名和授权码
return new PasswordAuthentication("发件人邮箱", "授权码,可以再邮箱的设置部分找到并开启");
}
});
//2、通过session获取transport对象
Transport transport = session.getTransport();
//3、通过transport对象邮箱用户名和授权码连接邮箱服务器
transport.connect("smtp.qq.com", "发件人邮箱,跟上面一样", "授权码,跟上面一样");
//4、创建邮件,传入session对象
MimeMessage mimeMessage = complexEmail(session, id);
//5、发送邮件
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
//6、关闭连接
transport.close();
}
2.创建邮件的方法,id同样是自定义所需
public MimeMessage complexEmail(Session session, String id) throws MessagingException, IOException, SQLException {
Map<String, String> map = putExcel(id);
String filePath = map.get("filePath");
File file = new File(filePath);
String fileName = map.get("fileName");
//消息的固定信息
MimeMessage mimeMessage = new MimeMessage(session);
//发件人
mimeMessage.setFrom(new InternetAddress("发件人邮箱"));
//收件人
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮箱"));
//邮件标题
mimeMessage.setSubject(fileName);
//邮件内容
//准备文本
MimeBodyPart text = new MimeBodyPart();
text.setContent(fileName, "text/html;charset=utf-8");
//附件
MimeBodyPart appendix = new MimeBodyPart();
appendix.setDataHandler(new DataHandler(new FileDataSource(file)));
appendix.setFileName(fileName + ".xls");
//拼装邮件正文
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(text);
mimeMultipart.setSubType("related");//文本和图片内嵌成功
//将拼装好的正文内容设置为主体
MimeBodyPart contentText = new MimeBodyPart();
contentText.setContent(mimeMultipart);
//拼接附件
MimeMultipart allFile = new MimeMultipart();
allFile.addBodyPart(appendix);//附件
allFile.addBodyPart(contentText);//正文
allFile.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed
//放到Message消息中
mimeMessage.setContent(allFile);
mimeMessage.saveChanges();//保存修改
return mimeMessage;
}
整套代码就是这些了,其中用到的自定义的方法putExcel(String id)在上一篇文章中有写到,是关于POI操作Excel的,有需要的朋友可以看下
代码注释很详细,有不懂得可以私信