首先引入 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