利用JavaMail发邮件

初次接触javamail的人学习javamail很容易出错。下面给个成形的例子出来,希望对初学者有所帮助。

1。在官网上下一个mail.jar

 

MyAuthenticator

package com.yang.hai;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MyAuthenticator extends Authenticator {
 private String strUser;
    private String strPwd;
    public MyAuthenticator(String user, String password) {
      this.strUser = user;
      this.strPwd = password;
    }
    protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(strUser, strPwd);
    }
 }

MailExample

 

package com.yang.hai;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailExample {
 public static void main (String args[]) throws Exception {    
     String host = "smtp.sohu.com";   //发件人使用发邮件的电子信箱服务器
     String from = "##@sohu.com";    //发邮件的出发地(发件人的信箱)
     String to = "##@163.com";   //发邮件的目的地(收件人信箱)
     Properties props = System.getProperties();  
     props.put("mail.smtp.host", host);  
     props.put("mail.smtp.auth", "true");
//这样才能通过验证
     MyAuthenticator myauth = new MyAuthenticator(from, "##");
     Session session = Session.getDefaultInstance(props, myauth);
//     session.setDebug(true);
     // Define message
     MimeMessage message = new MimeMessage(session);
     // Set the from address
     message.setFrom(new InternetAddress(from));
     // Set the to address
     message.addRecipient(Message.RecipientType.TO,
       new InternetAddress(to));
     // Set the subject
     message.setSubject("测试程序!");
     message.setText("这是用java写的发送电子邮件的测试程序!");
        Transport transport = session.getTransport("smtp");
        transport.send(message);
       transport.close();
   }
}

如果出现这个异常

Exception in thread "main" javax.mail.SendFailedException: Sending failed;
  nested exception is:
 class javax.mail.MessagingException: 451 4.2.1 CONTENT REJECT:sohu engine content reject [email protected]:http://mail.sohu.com/info/policy/14

 at javax.mail.Transport.send0(Transport.java:218)
 at javax.mail.Transport.send(Transport.java:80)
 at com.hyq.test.MailExample.main(MailExample.java:30)

不用担心是搜狐服务器比较繁忙的标志

 

 

 

你可能感兴趣的:(java,thread)