java发送mail

首先引入 mail.jar  activaction.jar

我用的是163邮箱  登录账号+授权码

 

下面直接贴代码

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;
     }
}

经测试 163和公司服务器都能收到邮件 但是QQ邮箱毛病多~~ 很多邮件都被拒掉了!!!

爆的异常  只是因为标题或内容被认为垃圾邮件  改下内容和标题就好

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)

posted @ 2017-01-04 15:14  天空_Good  阅读(1194)  评论(1编辑  收藏  举报