JavaMail本地伺服器傳送郵件
阿新 • • 發佈:2019-01-10
Java利用自己的郵箱傳送郵件需要一下兩個jar包
activation.jar 下面為下載地址及方法
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-plat-419418.html#7017-jaf-1.1.1-oth-JPR
mail.jar下面為下載地址及方法
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-eeplat-419426.html#javamail-1.4.7-oth-JPR
package com.nuanshui.frms.exchange.demo.utils;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.FileOutputStream;
import java.util.Properties;
public class EmailUtil {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host", "傳送伺服器地址");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
//使用JavaMail傳送郵件的5個步驟
//1、建立session
Session session = Session.getInstance(prop);
//開啟Session的debug模式,這樣就可以檢視到程式傳送Email的執行狀態
session.setDebug(true);
//2、通過session得到transport物件
Transport ts = session.getTransport();
//3、連上郵件伺服器
ts.connect("傳送伺服器地址", "本地郵箱", "郵箱密碼");
//4、建立郵件
Message message = createAttachMail(session);
//5、傳送郵件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
/**
* @Method: createAttachMail
* @Description: 建立一封帶附件的郵件
*
* @param session
* @return
* @throws Exception
*/
public static MimeMessage createAttachMail(Session session) throws Exception{
MimeMessage message = new MimeMessage(session);
//設定郵件的基本資訊
//發件人
message.setFrom(new InternetAddress("發件人郵箱 "));
//收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("收件人郵箱"));
//郵件標題
message.setSubject("標題");
//建立郵件正文,為了避免郵件正文中文亂碼問題,需要使用charset=UTF-8指明字元編碼
MimeBodyPart text = new MimeBodyPart();
text.setContent("郵件文字內容", "text/html;charset=UTF-8");
//建立郵件附件
MimeBodyPart attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("D:/附件地址/附件名稱.xlsx"));
attach.setDataHandler(dh);
attach.setFileName(dh.getName()); //
//建立容器描述資料關係
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(text);
mp.addBodyPart(attach);
mp.setSubType("mixed");
message.setContent(mp);
message.saveChanges();
//將建立的Email寫入到E盤儲存
message.writeTo(new FileOutputStream("d:\\attachMail.eml"));
//返回生成的郵件
return message;
}
}