java mail實現Email的傳送,完整程式碼
package com.sycamore.controller;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
public class test {
sendMail();
}
public static void sendMail(){
/*
* 1.文字內容
* */
StringBuffer buffer = new StringBuffer();
buffer.append("姓名:小明").append("\n");
buffer.append("年齡:18").append("\n");
buffer.append("愛好:打籃球").append("\n");
buffer.append(" ---來自官網").append("\n");
/*
* 2.配置協議
Properties props = new Properties();
//協議
props.setProperty("mail.transport.protocol", "smtps");
//伺服器
props.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
//埠
props.setProperty("mail.smtp.port", "25");
//使用smtp身份驗證
//使用SSL,企業郵箱必需!
//開啟安全協議
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
//傳送郵箱賬號密碼
Session mailSession = Session.getDefaultInstance(props, new MyAuthenricator("傳送者郵箱賬號", "傳送者郵箱密碼"));
/*
* 3.配置郵件會話之後,要編寫訊息
*要編寫訊息就要生成javax.mail.Message子類的例項或對Internet郵件使用javax.mail.interet.MimeMessage類。
* */
MimeMessage mimeMessage = new MimeMessage(mailSession);
try {
//訊息傳送者、日期、主題
mimeMessage.setFrom(new InternetAddress("傳送者郵箱賬號"));
mimeMessage.setSentDate(new Date());
mimeMessage.setSubject("java郵箱測試");
//設定訊息的接受者與傳送者(定址接收)
mimeMessage.addRecipient(RecipientType.TO , new InternetAddress("接受者郵箱賬號"));
//設定訊息內容
mimeMessage.setText(buffer.toString());
/*
* 4.傳送Email,這裡以文字訊息為例
* */
// 儲存傳送資訊
mimeMessage.saveChanges();
//定義傳送協議
Transport transport = mailSession.getTransport("smtp");
//登入郵箱
//transport.connect("賬號","密碼");
//傳送郵件
transport.send(mimeMessage);
System.out.println("訊息傳送成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 在真正使用建立的過程中,往往會讓我們驗證密碼,這是我們要寫一個密碼驗證類。javax.mail.Authenticator是一個抽象類,
* 我們要寫MyAuthenticator的密碼驗證類,該類繼承Authenticator實現:
* */
//使用者名稱密碼驗證,需要實現抽象類Authenticator的抽象方法PasswordAuthentication
static class MyAuthenricator extends Authenticator{
String u = null;
String p = null;
public MyAuthenricator(String u,String p){
this.u=u;
this.p=p;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(u,p);
}
}
}
這個地方要注意 這兩個賬號要一致!
設定附件:
MimeMultipart multipart = new MimeMultipart();
File file = new File
MimeBodyPart affixPart = new MimeBodyPart();
affixPart.setDataHandler(new DataHandler(new FileDataSource(file)));// 讀取附件
affixPart.setFileName(MimeUtility.encodeText(file.getName()));//設定附件標題
multipart.addBodyPart(affixPart,個數);// 設定附件
詳細講解:http://blog.csdn.net/karem/article/details/4646071
希望能幫到你!