JAVA程式設計112——郵件傳送
阿新 • • 發佈:2018-11-08
package com.mollen.utils;
import org.junit.Test;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
/**
* @ClassName: SendMail
* @Auther: Mollen
* @CreateTime: 2018-10-17 23:56:36
* @Description:
* 簡單郵件傳送封裝工具類:
* qq郵箱可用:已經通過測試
*/
public class SendMailUtils {
/**
* 1.靜態成員變數
*/
private static Properties props; // 初始化引數
private static InternetAddress sendMan = null; // 發件人地址
private static String userName = "[email protected]"; // 發件人的郵箱地址
private static String password = "pijwmdxjijejdehf"; // 發件人的密碼(授權碼)
//網路引數
static {
props = new Properties();
props.put("mail.transport.protocol", "smtp"); // 指定協議
props.put("mail.smtp.host", "smtp.qq.com"); // 主機 smtp.qq.com
props.put("mail.smtp.port", 25); // 埠
props.put("mail.smtp.auth", "true"); // 使用者密碼認證
//props.put("mail.debug", "true"); // 除錯模式
try {
//建立地址物件
sendMan = new InternetAddress(userName);
} catch (AddressException e) {
throw new RuntimeException(e);
}
}
/**
* 2.靜態方法用於傳送郵件
*
*/
public static void sendMail(String to ,String title,String text) throws AddressException, MessagingException {
Session session = Session.getInstance(props); // 建立郵件會話
MimeMessage msg = new MimeMessage(session); // 建立郵件物件
msg.setFrom(sendMan); // 設定發件人
msg.setRecipients(Message.RecipientType.TO,to); // 設定郵件收件人
msg.setSubject(title); // 標題
msg.setSentDate(new Date()); // 傳送時間
msg.setContent(text, "text/html;charset=UTF-8"); // 傳送內容
// 傳送
try{
Transport trans = session.getTransport();
trans.connect(userName, password);
trans.sendMessage(msg, msg.getAllRecipients());
System.out.println("傳送完成...");
trans.close();
}catch(Exception e){
System.out.println("傳送失敗...");
e.printStackTrace();
}
}
@Test
public void test(){
try {
SendMailUtils.sendMail("[email protected]","收到一封新郵件","Hello Mail!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}