1. 郵件發送所需的jar包
郵件發送需要兩個jar包
<!--支持郵件發送的jar包-->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
2. 普通的郵件發送
只發送文字內容
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class MailDemo01 {
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");//需要驗證用戶密碼
//設置SSL加密,QQ郵箱才有
MailSSLSocketFactory sf=new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
//使用javaMail發送郵件的6個步驟
//1.創建定義整個應用程序所需要的環境信息的session對象
//QQ郵箱才有,其他郵箱就不用
Session session=Session.getDefaultInstance(prop, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//發件人郵件用戶名、授權碼
return new PasswordAuthentication("發件人的QQ郵箱","授權碼");
}
});
//開啟session的debug模式,這樣可以查看到程序發送Email的運行狀態
session.setDebug(true);
//2.通過session得到transport對象
Transport ts=session.getTransport();
//3.使用郵箱的用戶名和授權碼連上郵件服務器
ts.connect("smtp.qq.com","發件人的QQ郵箱","授權碼");
//4.創建郵件:寫文件
//注意需要傳遞session
MimeMessage message=new MimeMessage(session);
//指明郵件的發件人
message.setFrom(new InternetAddress("發件人的QQ郵箱"));
//指明郵件的收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress("收件人的QQ郵箱"));
//郵件標題
message.setSubject("郵件標題");
//郵件的文本內容
message.setContent("驗證碼為:123456,請不要泄露,如果不是本人操作請忽略","text/html;charset=UTF-8");
//5.發送郵件
ts.sendMessage(message,message.getAllRecipients());
//6.關閉連接
ts.close();
}
}
3. 發送圖片的郵件發送
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
public class MailDemo02 {
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("發送者的qq郵箱","授權碼");
}
});
//開啟session的debug模式,這樣可以查看到程序發送Email的運行狀態
session.setDebug(true);
//2.通過session得到transport對象
Transport ts=session.getTransport();
//3.使用郵箱的用戶名和授權碼連上郵件服務器
ts.connect("smtp.qq.com","發送者的QQ郵箱","授權碼");
//4.創建郵件:寫文件
//注意需要傳遞session
MimeMessage message=new MimeMessage(session);
//指明郵件的發件人
message.setFrom(new InternetAddress("發送者的QQ郵箱"));
//指明郵件的收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress("收件人的QQ郵箱"));
//郵件標題
message.setSubject("郵件標題");
//郵件的文本內容
//=================================准備圖片數據=======================================
MimeBodyPart image=new MimeBodyPart();
//圖片需要經過數據化的處理
DataHandler dh=new DataHandler(new FileDataSource("C:/Users/yhj/Desktop/aaa.png"));
//在part中放入這個處理過圖片的數據
image.setDataHandler(dh);
//給這個part設置一個ID名字
image.setContentID("aaa.png");
//准備正文的數據
MimeBodyPart text=new MimeBodyPart();
text.setContent("這是一張正文<img src='cid:aaa.png'>","text/html;charset=UTF-8");
//描述數據關系
MimeMultipart mm=new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");
//設置到消息中,保存修改
message.setContent(mm);
message.saveChanges();
//5.發送郵件
ts.sendMessage(message,message.getAllRecipients());
//6.關閉連接
ts.close();
}
}
4. 混合發送郵件
發送文字,圖片和附件
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class MailDemo03 {
public static void main(String[] args) throws MessagingException, GeneralSecurityException {
//創建一個配置文件保存並讀取信息
Properties properties = new Properties();
//設置qq郵件服務器
properties.setProperty("mail.host","smtp.qq.com");
//設置發送的協議
properties.setProperty("mail.transport.protocol","smtp");
//設置用戶是否需要驗證
properties.setProperty("mail.smtp.auth", "true");
//=================================只有QQ存在的一個特性,需要建立一個安全的鏈接========================
// 關於QQ郵箱,還要設置SSL加密,加上以下代碼即可
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//=================================准備工作完畢================================================
//1.創建一個session會話對象;
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("發送者的qq郵箱", "授權碼");
}
});
//可以通過session開啟Dubug模式,查看所有的過程
session.setDebug(true);
//2.獲取連接對象,通過session對象獲得Transport,需要捕獲或者拋出異常;
Transport tp = session.getTransport();
//3.連接服務器,需要拋出異常;
tp.connect("smtp.qq.com","發送者的QQ郵箱","授權碼");
//4.連接上之后我們需要發送郵件;
MimeMessage mimeMessage = imageMail(session);
//5.發送郵件
tp.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
//6.關閉連接
tp.close();
}
public static MimeMessage imageMail(Session session) throws MessagingException {
//消息的固定信息
MimeMessage mimeMessage = new MimeMessage(session);
//郵件發送人
mimeMessage.setFrom(new InternetAddress("發送者的QQ郵箱"));
//郵件接收人,可以同時發送給很多人
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("接收者的QQ郵箱"));
mimeMessage.setSubject("郵件主題"); //郵件主題
/*
編寫郵件內容
1.圖片
2.附件
3.文本
*/
//圖片
MimeBodyPart body1 = new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("E:\\IDEA\\IdeaProjects\\fileDownload\\src\\main\\resources\\aaa.png")));
body1.setContentID("aaa.png"); //圖片設置ID
//文本
MimeBodyPart body2 = new MimeBodyPart();
body2.setContent("測試圖片<img src='cid:aaa.png'>","text/html;charset=utf-8");
//附件
MimeBodyPart body3 = new MimeBodyPart();
body3.setDataHandler(new DataHandler(new FileDataSource("E:\\IDEA\\IdeaProjects\\fileDownload\\src\\main\\resources\\log4j.properties")));
body3.setFileName("log4j.properties"); //附件設置名字
MimeBodyPart body4 = new MimeBodyPart();
body4.setDataHandler(new DataHandler(new FileDataSource("E:\\IDEA\\IdeaProjects\\fileDownload\\src\\main\\resources\\a.txt")));
body4.setFileName("a.txt"); //附件設置名字
//拼裝郵件正文內容
MimeMultipart multipart1 = new MimeMultipart();
multipart1.addBodyPart(body1);
multipart1.addBodyPart(body2);
multipart1.setSubType("related"); //1.文本和圖片內嵌成功!
//new MimeBodyPart().setContent(multipart1); //將拼裝好的正文內容設置為主體
MimeBodyPart contentText = new MimeBodyPart();
contentText.setContent(multipart1);
//拼接附件
MimeMultipart allFile =new MimeMultipart();
allFile.addBodyPart(body3); //附件
allFile.addBodyPart(body4); //附件
allFile.addBodyPart(contentText);//正文
allFile.setSubType("mixed"); //正文和附件都存在郵件中,所有類型設置為mixed;
//放到Message消息中
mimeMessage.setContent(allFile);
mimeMessage.saveChanges();//保存修改
return mimeMessage;
}
}
以上內容參考自狂神說java