pom.xml
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api --> <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.6.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail --> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency>
EmailUtils:
package com.nextjoy.projects.monitor.utils; import com.sun.mail.util.MailSSLSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.security.GeneralSecurityException; import java.util.Properties; /** * 用户发送邮件 * Created by liuxn. * 2018/12/6 */ public class EmailUtils { private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class); private static String EMAIL_FROM_SMTP_HOST = PropertyUtils.getConfigValue("email.from.smtp.host"); //是否开启验证 private static String EMAIL_FROM_SMTP_AUTH = PropertyUtils.getConfigValue("mail.from.smtp.auth"); private static String EMAIL_FROM_SMTP_PORT = PropertyUtils.getConfigValue("email.from.smtp.port"); private String username; private String password; public EmailUtils(String username, String password) { this.username = username; this.password = password; } /** * 发送文本邮件 * * @param fromEmail 发送人邮箱 * @param toEmail 接受人邮箱 * @param title 标题 * @param text 发送内容 */ public void sendEmails(String fromEmail, String toEmail, String title, String text) { logger.info("fromEmail:[" + fromEmail + "],toEmail:[" + toEmail + "],title:[" + title + "],text:[" + text + "]"); try { // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", EMAIL_FROM_SMTP_HOST); //设置端口 properties.setProperty("mail.smtp.port", EMAIL_FROM_SMTP_PORT); //是否验证 properties.put("mail.smtp.auth", EMAIL_FROM_SMTP_AUTH); //开启SSL MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); // 获取默认session对象 Session session = Session.getDefaultInstance(properties); // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set From: 头部头字段 message.setFrom(new InternetAddress(fromEmail)); // Set To: 头部头字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); // Set Subject: 头部头字段 message.setSubject(title); // 设置消息体 message.setText(text); // 发送消息 Transport.send(message, username, password); logger.info("Sent email successfully ...."); } catch (Exception e) { logger.error("send email fail ", e); } } }
调用:
EmailUtils emailUtils = new EmailUtils(EMAIL_FROM_USERNAME, EMAIL_FROM_PASSWORD);//初始化发送者邮箱用户名密码 emailUtils.sendEmails(EMAIL_FROM_ADDRESS,EMAIL_TO_ADDRESS,title,text);