Java 郵件(JavaMail)
- 創(chuàng)建MailSenderInfo Bean,用來存儲郵件使用的基本信息。
/**
* 1. 發(fā)送郵件需要使用的基本信息
* @author mazaiting
*/
public class MailSenderInfo {
/** 發(fā)送郵件的服務器ip */
private String mailServerHost;
/** 發(fā)送郵件的服務器端口 */
private String mailServerPort = "25";
/** 郵件發(fā)送者的地址 */
private String fromAddress;
/** 郵件接收者的地址 */
private String toAddress;
/** 登錄郵件發(fā)送服務器的用戶名 */
private String username;
/** 登錄郵件發(fā)送服務器的密碼 --授權密碼*/
private String password;
/** 是否需要身份驗證 */
private boolean isValidate = false;
/** 郵件主題 */
private String subject;
/** 郵件文本內容 */
private String content;
/** 郵件附件的文件 */
private List<File> fileList;
/**
* 獲得郵件會話屬性
* @throws GeneralSecurityException 證書安全異常
*/
public Properties getProperties() throws GeneralSecurityException {
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", isValidate ? "true" : "false");
// 進行證書驗證
MailSSLSocketFactory mssf = new MailSSLSocketFactory();
mssf.setTrustAllHosts(true);
p.put("mail.smtp.ssl.enable", true);
p.put("mail.smtp.ssl.socketFactory", mssf);
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 String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isValidate() {
return isValidate;
}
public void setValidate(boolean isValidate) {
this.isValidate = isValidate;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<File> getFileList() {
return fileList;
}
public void setFileList(List<File> fileList) {
this.fileList = fileList;
}
}
- 密碼驗證管理
/**
* 2. 簡單的驗證管理
* @author mazaiting
*/
public class SimpleAuthenticator extends Authenticator{
/**用戶名*/
private String username = null;
/**密碼*/
private String password = null;
public SimpleAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
- 實現簡單郵件服務器
/**
* 3. 簡單郵件
* @author mazaiting
*/
public class SimpleMailServer {
/**
* 以文本格式發(fā)送郵件
* @param mailInfo 待發(fā)送的郵件信息
* @return true 發(fā)送成功; false 發(fā)送不成功
*/
public boolean sendTextMail(MailSenderInfo mailInfo) {
try {
// 判斷是否需要身份驗證
SimpleAuthenticator authenticator = null;
Properties properties = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份驗證, 則創(chuàng)建一個密碼驗證器
authenticator = new SimpleAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());
}
// 根據郵件會話屬性和密碼驗證器構造一個發(fā)送郵件的Session
Session sendMailSession = Session.getDefaultInstance(properties, authenticator);
// 根據Session創(chuàng)建一個郵件信息
Message mailMessage = new MimeMessage(sendMailSession);
// 創(chuàng)建郵件發(fā)送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 設置郵件消息的發(fā)送者
mailMessage.setFrom(from);
// 創(chuàng)建郵件的接收者地址,并設置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO, to);
// 設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設置郵件消息發(fā)送時間
mailMessage.setSentDate(new Date());
// 設置郵件消息的主要內容
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
// 發(fā)送郵件
Transport.send(mailMessage);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 以HTML格式發(fā)送郵件
*
* @param mailInfo
* 待發(fā)送的郵件
* @return true 發(fā)送成功; false 發(fā)送失敗。
*/
public boolean sendHtmlMail(MailSenderInfo mailInfo) {
try {
// 判斷是否需要身份認證
SimpleAuthenticator authenticator = null;
Properties properties = mailInfo.getProperties();
// 如果需要身份認證, 則創(chuàng)建一個密碼驗證器
if (mailInfo.isValidate()) {
authenticator = new SimpleAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());
}
// 根據郵件會話屬性和密碼驗證器構造一個發(fā)送郵件的Session
Session sendMailSession = Session.getDefaultInstance(properties, authenticator);
// 根據Session創(chuàng)建一個郵件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 創(chuàng)建郵件發(fā)送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 設置郵件消息的發(fā)送者
mailMessage.setFrom(from);
// 創(chuàng)建郵件的接收者地址, 并設置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO屬性表示接收者的類型為TO
mailMessage.setRecipient(Message.RecipientType.TO, to);
// 設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設置郵件消息發(fā)送的時間
mailMessage.setSentDate(new Date());
// MiniMultipart類是一個容器,包含MimeBodyPart類型的對象
Multipart mainPart = new MimeMultipart();
if (null != mailInfo.getContent()) {
setContent(mailInfo, mainPart);
}
if (null != mailInfo.getFileList() && mailInfo.getFileList().size() > 0) {
addAttachment(mailInfo.getFileList(), mainPart);
}
// 將MiniMultipart對象設置為郵件內容
mailMessage.setContent(mainPart);
// 發(fā)送郵件
Transport.send(mailMessage);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 設置內容
* @param mailInfo 郵件信息
* @param mainPart 容器
* @throws MessagingException 消息異常
*/
public void setContent(MailSenderInfo mailInfo, Multipart mainPart) throws MessagingException {
// 創(chuàng)建一個包含HTML內容的MimeBodyPart
BodyPart textContent = new MimeBodyPart();
// 設置HTML內容
textContent.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(textContent);
}
/**
* 添加附件
* @param filePath 文件路徑
* @param fileName 文件名
* @param mainPart 容器
* @throws MessagingException 消息異常
*/
public void addAttachment(List<File> fileList, Multipart mainPart) throws MessagingException{
for (int i = 0; i < fileList.size(); i++){
File file = fileList.get(i);
BodyPart fileContent = new MimeBodyPart();
DataSource source = new FileDataSource(file.getAbsolutePath());
fileContent.setDataHandler(new DataHandler(source));
fileContent.setFileName(file.getName());
mainPart.addBodyPart(fileContent);
}
}
}
- 主函數使用
public class Client {
public static void main(String[] args) {
// 設置郵件
MailSenderInfo mailInfo = new MailSenderInfo();
// 設置服務器主機名
mailInfo.setMailServerHost("smtp.qq.com");
// 設置服務器端口
mailInfo.setMailServerPort("465");
// 設置密碼驗證
mailInfo.setValidate(true);
// 設置用戶名
mailInfo.setUsername("1449689807@qq.com");
// 設置登錄驗證需要的密碼
mailInfo.setPassword("****************");// 設置為自己的驗證密碼
// 設置發(fā)送者地址
mailInfo.setFromAddress("1449689807@qq.com");
// 設置接收者地址
mailInfo.setToAddress("1425941077@qq.com");
// 設置郵件標題
mailInfo.setSubject("郵件標題");
// 設置郵件內容
mailInfo.setContent("郵件內容");
// 設置郵件攜帶的附件
// List<File> fileList = new ArrayList<>();
// fileList.add(new File("C:\\Users\\Administrator\\Desktop\\password.png"));
// mailInfo.setFileList(fileList);
// 發(fā)送郵件
SimpleMailServer sms = new SimpleMailServer();
// sms.sendTextMail(mailInfo);// 發(fā)送文本格式
sms.sendHtmlMail(mailInfo);// 發(fā)送html格式
}
}
遇到的問題
查看詳情Android 使用Javamail發(fā)送郵件時,要將第一步中的getProperties()函數更改為如下內容:
/**
* 獲得郵件會話屬性
* @throws GeneralSecurityException 證書安全異常
*/
Properties getProperties() throws GeneralSecurityException {
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", isValidate ? "true" : "false");
// 進行證書驗證
MailSSLSocketFactory mssf = new MailSSLSocketFactory();
mssf.setTrustAllHosts(true);
p.put("mail.smtp.ssl.enable", true);
p.put("mail.smtp.ssl.socketFactory", mssf);
return p;
}
其中需要activation.jar,點擊下載。或者Gradle直接依賴compile 'com.sun.mail:android-mail:1.6.0',使用Gradle依賴之后,之前用到的mail.jar與此處用到的activation.jar都必須要刪除,否則會重復編譯jar。