首先引入 mail.jar activaction.jarhtml
我用的是163郵箱 登陸帳號+受權碼java
下面直接貼代碼服務器
package mail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* @author 做者 天空:
* @date 建立時間:2016年9月29日 上午11:46:43
*
*/
public class MailDemo {
public static void main(String [] args) throws MessagingException{
Properties pro = new Properties();
pro.setProperty("mail.host", "發件服務器 如smtp.163.com");
pro.setProperty("mail.transport.protocol", "smtp");
pro.setProperty("mail.smtp.auth", "true");
//建立session
Session session = Session.getInstance(pro,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("郵箱帳號", "受權碼");
}
});
session.setDebug(true);
//經過session獲取transport
Transport ts = session.getTransport();
MimeMessage msg = textMail(session);
ts.send(msg,msg.getAllRecipients());
ts.close();
}
/**
* 只發送文本
* @throws MessagingException
* @throws AddressException
*/
public static MimeMessage textMail(Session session) throws AddressException, MessagingException{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("發件人地址"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress("收件人地址"));
message.setSubject("公司日程");
message.setContent("明天休假一天", "text/html;charset=UTF-8");
return message;
}
}session
經測試 163和公司服務器都能收到郵件 可是QQ郵箱毛病多~~ 不少郵件都被拒掉了!!! 測試
爆的異常 只是由於標題或內容被認爲垃圾郵件 改下內容和標題就好spa
DEBUG SMTP: MessagingException while sending, THROW:
com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 163 smtp13,EcCowADHqvxEoGxYP_KEFw--.42031S2 1483513935,please see http://mail.163.com/help/help_spam_16.htm?ip=1.202.100.147&hostid=smtp13&time=1483513935
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2267)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:2045)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1260)
at javax.mail.Transport.send0(Transport.java:255)
at javax.mail.Transport.send(Transport.java:146)
at mail.MailDemo.main(MailDemo.java:36)htm