pom.xml
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.6</version> </dependency>
MailSenderInfo.java
import com.sun.mail.util.MailSSLSocketFactory; import java.security.GeneralSecurityException; import java.util.Properties; public class MailSenderInfo { // 發送郵件的服務器的IP和端口 private String mailServerHost; private String mailServerPort = "25"; // 郵件發送者的地址 private String fromAddress; // 郵件接收者的地址 private String toAddress; private String password; // 是否需要身份驗證 private boolean validate = false; // 郵件主題 private String subject; // 郵件的文本內容 private String content; // 郵件附件的文件名 private String[] attachFileNames; //郵件發件人昵稱 private String nick; private boolean ssl; public String getNick() { return nick; } public boolean isSsl() { return ssl; } public void setSsl(boolean ssl) { this.ssl = ssl; } public void setNick(String nick) { this.nick = nick; } private String httpServer; private MailType type = MailType.TEXT;//html or text; enum MailType { TEXT, HTML; } /** */ /** * 獲得郵件會話屬性 */ 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"); if (ssl) { try { MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); p.put("mail.smtp.ssl.enable", "true"); p.put("mail.smtp.ssl.socketFactory", sf); } catch (GeneralSecurityException e) { } } 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 getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String textContent) { this.content = textContent; } public String getHttpServer() { return httpServer; } public void setHttpServer(String httpServer) { this.httpServer = httpServer; } public MailType getType() { return type; } public void setType(MailType type) { this.type = type; } @Override public String toString() { return "MailSenderInfo [mailServerHost=" + mailServerHost + ", mailServerPort=" + mailServerPort + ", fromAddress=" + fromAddress + ", toAddress=" + toAddress + ", content=" + content + ", httpServer=" + httpServer + ", type=" + type + "]"; } }
MyAuthenticator.java
import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; 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; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }
Test.java
import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.util.Date; import java.util.Properties; /** * @author jiash * @since 2021/10/8 */ public class Test { private static final String CHARSET = "UTF-8"; public static boolean sendTextMail(MailSenderInfo mailInfo) { MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份認證,則創建一個密碼驗證器 authenticator = new MyAuthenticator(mailInfo.getFromAddress(), mailInfo.getPassword()); } Session sendMailSession = Session.getInstance(pro, authenticator); try { // 根據session創建一個郵件通知 MimeMessage mailMessage = new MimeMessage(sendMailSession); // 創建郵件發送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); if (mailInfo.getNick() != null && !"".equals(mailInfo.getNick())) { String nickName; try { nickName = javax.mail.internet.MimeUtility.encodeText(mailInfo.getNick()); mailMessage.setFrom(new InternetAddress(nickName + " <" + from + ">")); } catch (Exception e) { } } else { // 設置郵件通知的發送者 mailMessage.setFrom(from); } // 創建郵件的接收者地址,並設置到郵件通知中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO, to); // 設置郵件通知的主題 mailMessage.setSubject(mailInfo.getSubject(), CHARSET); // 設置郵件通知發送的時間 mailMessage.setSentDate(new Date()); Multipart mp = new MimeMultipart(); MimeBodyPart mbpContent = new MimeBodyPart(); mbpContent.setContent(mailInfo.getContent(), "text/plain;charset=utf-8"); mp.addBodyPart(mbpContent); if (mailInfo.getAttachFileNames() != null) { for (String fileName : mailInfo.getAttachFileNames()) { MimeBodyPart mbpFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(fileName); mbpFile.setDataHandler(new DataHandler(fds)); // 解決預發環境的發送郵件時附件的標題亂碼問題 mbpFile.setFileName(MimeUtility.encodeText(fds.getName())); mp.addBodyPart(mbpFile); } } // 設置郵件通知的主要內容 mailMessage.setContent(mp); // 發送郵件 Transport.send(mailMessage); return true; } catch (Exception ex) { } 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.getFromAddress(), mailInfo.getPassword()); } // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session Session sendMailSession = Session.getInstance(pro, authenticator); try { // 根據session創建一個郵件通知 MimeMessage 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(), CHARSET); // 設置郵件通知發送的時間 mailMessage.setSentDate(new Date()); // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象 Multipart mainPart = new MimeMultipart(); if (mailInfo.getAttachFileNames() != null) { /*MimeBodyPart mbpContent = new MimeBodyPart(); mbpContent.setContent(mailInfo.getContent(), "text/plain;charset=utf-8"); mainPart.addBodyPart(mbpContent);*/ for (String fileName : mailInfo.getAttachFileNames()) { MimeBodyPart mbpFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(fileName); mbpFile.setDataHandler(new DataHandler(fds)); // 解決預發環境的發送郵件時附件的標題亂碼問題 mbpFile.setFileName(MimeUtility.encodeText(fds.getName())); mainPart.addBodyPart(mbpFile); } } // 創建一個包含HTML內容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 設置HTML內容 html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); // 創建一個包含圖表的的MimeBodyPart // 將MiniMultipart對象設置為郵件內容 mailMessage.setContent(mainPart); // 發送郵件 Transport.send(mailMessage); return true; } catch (Exception ex) { } return false; } public static void main(String[] args) { MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.sina.net"); mailInfo.setPassword("解密后的明文密碼xxxxx"); mailInfo.setFromAddress("user@mail.xxxx.com"); mailInfo.setMailServerPort("25"); mailInfo.setValidate(true); mailInfo.setToAddress("1214369231@qq.com"); mailInfo.setSubject("測試主題"); mailInfo.setContent("測試一下"); sendTextMail(mailInfo); } }
原創文章,歡迎轉載,轉載慶注明出處!
