今天來記錄一下如何使用java來發送郵件
背景
之前項目有個需求,當產品出現故障時會把情況上送給服務器,服務器發送郵件將故障產品的位置以及故障信息等告知維修人員。發送郵件的接口不是我負責的,但是有興趣了解一下
正文
首先看一下實現的步驟,然后在講講有可能遇到的問題
1.引入javax.mail依賴,我用的是springboot,所以依賴是這樣引的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
沒用springboot框架的,自己去找一下
2.構建郵件基本信息類
package com.example.demo.comment.sendemail;
import java.util.Properties;
/**
* 發送郵件需要使用的基本信息
*
* @author 860118060
*/
public class MailSenderInfo {
/**
* 發送郵件的服務器的IP和端口
*/
private String mailServerHost;
private String mailServerPort = "25";
/**
* 郵件發送者的地址
*/
private String fromAddress;
/**
* 郵件接收者的地址
*/
private String toAddress;
/**
* 登陸郵件發送服務器的用戶名和密碼
*/
private String userName;
private String password;
/**
* 是否需要身份驗證
*/
private boolean validate = false;
/**
* 郵件主題
*/
private String subject;
/**
* 郵件的文本內容
*/
private String content;
/**
* 郵件附件的文件名
*/
private String[] attachFileNames;
/**
* 獲得郵件會話屬性
*/
public Properties getProperties() {
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
this.content = textContent;
}
}
3.構建郵件發送器
package com.example.demo.comment.sendemail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* 簡單郵件(不帶附件的郵件)發送器
*/
public class SimpleMailSender {
/**
* 以文本格式發送郵件
* @param mailInfo 待發送的郵件的信息
*/
public static boolean sendTextMail(MailSenderInfo mailInfo) {
// 判斷是否需要身份認證
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份認證,則創建一個密碼驗證器
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根據session創建一個郵件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 創建郵件發送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 設置郵件消息的發送者
mailMessage.setFrom(from);
// 創建郵件的接收者地址,並設置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設置郵件消息發送的時間
mailMessage.setSentDate(new Date());
// 設置郵件消息的主要內容
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
// 發送郵件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
/**
* 以HTML格式發送郵件
* @param mailInfo 待發送的郵件信息
*/
public static boolean sendHtmlMail(MailSenderInfo mailInfo){
// 判斷是否需要身份認證
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
//如果需要身份認證,則創建一個密碼驗證器
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根據session創建一個郵件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 創建郵件發送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 設置郵件消息的發送者
mailMessage.setFrom(from);
// 創建郵件的接收者地址,並設置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO屬性表示接收者的類型為TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設置郵件消息發送的時間
mailMessage.setSentDate(new Date());
// MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
Multipart mainPart = new MimeMultipart();
// 創建一個包含HTML內容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 設置HTML內容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 將MiniMultipart對象設置為郵件內容
mailMessage.setContent(mainPart);
// 發送郵件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
}
4.構建密碼驗證器
package com.example.demo.comment.sendemail;
import javax.mail.*;
/**
* @author 860118060
*/
public class MyAuthenticator extends Authenticator{
String userName=null;
String password=null;
public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
至此准備工作都完成了,下面看一下如何調用吧
5.調用Demo
package com.example.demo.comment.sendemail;
public class SendEmailDemo {
public static void main(String[] args){
//這個類主要是設置郵件
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost("smtp.163.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
// 發送方郵箱
mailInfo.setUserName("xxxxxxxx@163.com");
// 發送方郵箱密碼
mailInfo.setPassword("xxxxxxxx");
// 發送方郵箱
mailInfo.setFromAddress("xxxxxxxx@163.com");
// 接收方郵箱
mailInfo.setToAddress("xxxxxxxx@qq.com");
// 郵件標題
mailInfo.setSubject("測試用郵箱發送郵件");
// 郵件內容
mailInfo.setContent("<h1>郵件內容非常豐富<h1>");
//發送文體格式
SimpleMailSender.sendTextMail(mailInfo);
//發送html格式
SimpleMailSender.sendHtmlMail(mailInfo);
}
}
這里有兩種郵件發送格式


問題與總結
如果不出意外的話應該成功發送出兩封郵件了,但是凡事都有萬一,下面分析一下哪些問題會導致失敗呢?
1.mailInfo.setMailServerHost("smtp.163.com");與mailInfo.setFromAddress("xxxxxxxx@163.com");這兩句話。即如果你使用163smtp服務器,那么發送郵件地址就必須用163的郵箱,如果不的話,是不會發送成功的。
2.不要使用你剛剛注冊過的郵箱在程序中發郵件,如果你的163郵箱是剛注冊不久,那你就不要使用“smtp.163.com”。因為你發不出去。剛注冊的郵箱是不會給你這種權限的,也就是你不能通過驗證。要使用你經常用的郵箱,而且時間比較長的
3.qq郵箱作為發送方是有可能需要授權驗證的。
授權如下:
在設置里面找到賬戶,往下拉找到並按照提示開啟授權,然后將得到的授權碼作為郵箱密碼,即可成功發送郵件


最后順便附上常用郵箱:
常用的郵箱服務器(SMTP、POP3)地址、端口
sina.com:
POP3服務器地址:pop3.sina.com.cn(端口:110) SMTP服務器地址:smtp.sina.com.cn(端口:25)
sinaVIP:
POP3服務器:pop3.vip.sina.com (端口:110) SMTP服務器:smtp.vip.sina.com (端口:25)
sohu.com:
POP3服務器地址:pop3.sohu.com(端口:110) SMTP服務器地址:smtp.sohu.com(端口:25)
126郵箱:
POP3服務器地址:pop.126.com(端口:110) SMTP服務器地址:smtp.126.com(端口:25)
139郵箱:
POP3服務器地址:POP.139.com(端口:110) SMTP服務器地址:SMTP.139.com(端口:25)
163.com:
POP3服務器地址:pop.163.com(端口:110) SMTP服務器地址:smtp.163.com(端口:25)
QQ郵箱
POP3服務器地址:pop.qq.com(端口:110)
SMTP服務器地址:smtp.qq.com (端口:25)
QQ企業郵箱
POP3服務器地址:pop.exmail.qq.com (SSL啟用 端口:995) SMTP服務器地址:smtp.exmail.qq.com(SSL啟用 端口:587/465)
yahoo.com:
POP3服務器地址:pop.mail.yahoo.com SMTP服務器地址:smtp.mail.yahoo.com
yahoo.com.cn:
POP3服務器地址:pop.mail.yahoo.com.cn(端口:995) SMTP服務器地址:smtp.mail.yahoo.com.cn(端口:587
HotMail
POP3服務器地址:pop3.live.com (端口:995) SMTP服務器地址:smtp.live.com (端口:587)
gmail(google.com)
POP3服務器地址:pop.gmail.com(SSL啟用 端口:995) SMTP服務器地址:smtp.gmail.com(SSL啟用 端口:587)
263.net:
POP3服務器地址:pop3.263.net(端口:110) SMTP服務器地址:smtp.263.net(端口:25)
263.net.cn:
POP3服務器地址:pop.263.net.cn(端口:110) SMTP服務器地址:smtp.263.net.cn(端口:25)
x263.net:
POP3服務器地址:pop.x263.net(端口:110) SMTP服務器地址:smtp.x263.net(端口:25)
21cn.com:
POP3服務器地址:pop.21cn.com(端口:110) SMTP服務器地址:smtp.21cn.com(端口:25)
Foxmail:
POP3服務器地址:POP.foxmail.com(端口:110) SMTP服務器地址:SMTP.foxmail.com(端口:25)
china.com:
POP3服務器地址:pop.china.com(端口:110) SMTP服務器地址:smtp.china.com(端口:25)
tom.com:
POP3服務器地址:pop.tom.com(端口:110) SMTP服務器地址:smtp.tom.com(端口:25)
etang.com:
POP3服務器地址:pop.etang.com SMTP服務器地址:smtp.etang.com
在多說一句,本文檔不屬於教程,只是對自己學習的記錄,大家可以參考一下,如果有什么錯誤歡迎指出
有時間在看看怎么在郵件中添加附件並分享出來
本次學習主要參考:https://www.cnblogs.com/kiwifly/p/4435867.html
上次時間有限就沒有看如何添加附件,這次有時間整出來了,因為太簡單了所以就接着寫了。
只需要將發送html郵件的方法改動一下就行了,看一下代碼
/**
* 以HTML格式發送郵件
* @param mailInfo 待發送的郵件信息
*/
public static boolean sendHtmlMail(MailSenderInfo mailInfo){
// 判斷是否需要身份認證
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
//如果需要身份認證,則創建一個密碼驗證器
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根據session創建一個郵件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 創建郵件發送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 設置郵件消息的發送者
mailMessage.setFrom(from);
// 創建郵件的接收者地址,並設置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO屬性表示接收者的類型為TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設置郵件消息發送的時間
mailMessage.setSentDate(new Date());
// MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
Multipart mainPart = new MimeMultipart();
// 創建一個包含HTML內容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 設置HTML內容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
//添加郵件
// 注意這里是MimeBodyPart
MimeBodyPart part = new MimeBodyPart();
// 這里放附件的路徑(我就直接放桌面了)
part.attachFile("C:\\Users\\xxxxx\\Desktop\\123.PNG");
//多個附件也是一樣的,創建多個MimeBodyPart ,最后放入mainPart 里面
mainPart.addBodyPart(part);
// 將MiniMultipart對象設置為郵件內容
mailMessage.setContent(mainPart);
// 發送郵件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
