package com.jason.mail;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class EmailWithFile {
public static void main(String[] args) throws Exception {
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);
// 使用JavaMail发送邮件的5个步骤
// 1、创建定义整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 发件人邮箱用户名、授权码
return new PasswordAuthentication("xxx@qq.com", "授权码");
}
});
// 开始Session的debug模式,这样可以看到程序发送Email的运行状态
session.setDebug(true);
// 2、通过Session得到transport对象
Transport ts = session.getTransport();
// 3、使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com", "xxx@qq.com", "授权码");
// 4、创建邮件:写邮件
// 注意需要传递Session
MimeMessage message = mailWithImgAndFile(session);
// 5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
// 6、关闭连接
ts.close();
}
public static MimeMessage mailWithImgAndFile(Session session) throws Exception {
// 消息的固定信息
MimeMessage mimeMessage = new MimeMessage(session);
//指明发件人
mimeMessage.setFrom(new InternetAddress("xxx@qq.com"));
//指明收件人
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("xxx@qq.com"));
//邮件的标题
mimeMessage.setSubject("Java邮件发送带附件和图片");
/*
1、图片
2、附件
3、文本
*/
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("文件路径"));
image.setDataHandler(dh); //在body中放入这个处理的图片数据
image.setContentID("bz.jpg");//给图片设置一个ID,在后面使用
//准备文本数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片的邮件: <img src='cid:bz.jpg'>", "text/html;charset=utf-8");
//附件
MimeBodyPart file = new MimeBodyPart();
file.setDataHandler(new DataHandler(new FileDataSource("文件路径")));
file.setFileName("SimpleEmail.java");
// 接下来先将图片和文本拼接,得到multipart1,然后再把multipart1和文件进行拼接
MimeMultipart multipart1 = new MimeMultipart();
multipart1.addBodyPart(image);
multipart1.addBodyPart(text);
multipart1.setSubType("related");
//将拼装好的正文内容设置为主题
MimeBodyPart contentText = new MimeBodyPart();
contentText.setContent(multipart1);
//拼接文件
MimeMultipart addFile = new MimeMultipart();
addFile.addBodyPart(file);
addFile.addBodyPart(contentText); //正文(文本+图片)
addFile.setSubType("mixed");
//放到message消息中
mimeMessage.setContent(addFile);
mimeMessage.saveChanges();
return mimeMessage;
}
}
Java发送邮件(带图片和附件)
最新推荐文章于 2023-10-16 00:30:00 发布