<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.2</version> </dependency>
package com.bgi.util; import org.springframework.core.io.ClassPathResource; import javax.mail.Address; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.IOException; import java.util.Date; import java.util.Properties; public class EmailUtil {
//獲取屬性文件中的值,建議把配置的信息放到屬性文件中,方便修改和獲取 private static Properties properties = new Properties(); static{ try {
//加在屬性文件 properties.load(new ClassPathResource("properties/email.properties").getInputStream()); } catch (IOException e) { } } public static String SMTPSERVER = properties.getProperty("smtp.server"); //從屬性文件中獲取值其中key爲smtp.server public static String SMTPPORT = properties.getProperty("smtp.port"); //端口號 465 465 465 不是456 public static String ACCOUT = properties.getProperty("smtp.account");//帳戶名:個人是163帳戶,此帳戶必須在設置中開啓受權碼受權 public static String PWD = properties.getProperty("smtp.pwd"); //受權密碼 public static String users = properties.getProperty("email.users"); //這裏是發送給多個用戶多個用戶用都好分割xxx@xx.com,xxx@xx.com public static void sendEmail(String content){ try { // 建立郵件配置 Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); // 使用的協議(JavaMail規範要求) props.setProperty("mail.smtp.host", SMTPSERVER); // 發件人的郵箱的 SMTP 服務器地址 props.setProperty("mail.smtp.port", SMTPPORT); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.auth", "true"); // 須要請求認證 props.setProperty("mail.smtp.ssl.enable", "true");// 開啓ssl // 根據郵件配置建立會話,注意session別導錯包 Session session = Session.getDefaultInstance(props); // 開啓debug模式,能夠看到更多詳細的輸入日誌 session.setDebug(true); //建立郵件 MimeMessage message = createEmail(session,users,content); //將用戶和內容傳遞過來 //獲取傳輸通道 Transport transport = session.getTransport(); transport.connect(SMTPSERVER,ACCOUT, PWD); //鏈接,併發送郵件 transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); } } public static MimeMessage createEmail(Session session,String users,String content) throws Exception { // 根據會話建立郵件 MimeMessage msg = new MimeMessage(session); // address郵件地址, personal郵件暱稱, charset編碼方式 InternetAddress fromAddress = new InternetAddress(ACCOUT, "中間件推送", "utf-8"); // 設置發送郵件方 msg.setFrom(fromAddress); // 單個能夠直接這樣建立 // InternetAddress receiveAddress = new InternetAddress(); // 設置郵件接收方 Address[] internetAddressTo = new InternetAddress().parse(users);
//type:
要被設置爲 TO, CC 或者 BCC,這裏 CC 表明抄送、BCC 表明祕密抄送。舉例:Message.RecipientType.TO
msg.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo); // 設置郵件標題 msg.setSubject("測試標題", "utf-8"); msg.setText(content); // 設置顯示的發件時間 msg.setSentDate(new Date()); // 保存設置 msg.saveChanges(); return msg; } }
smtp.server=smtp.163.com smtp.port=465 smtp.account=xxx@163.com smtp.pwd=xxxxx email.users=xxx@163.com,xxxx@qq.com,xxx@xx.cn