javaMail发邮件 简单小例子

源:http://my.oschina.net/u/865478/blog/94154
评:
package com.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.InternetAddress;

import com.sun.mail.smtp.SMTPMessage;

class SimpleAuthenticator extends Authenticator{
private String userName;
private String password;
public SimpleAuthenticator(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication() {     
         return new PasswordAuthentication(this.userName, this.password); 
  
     } 


}
public class SendMail {


public static void sendMail(){
String userName = "[email protected]";
String password="xxxxxxx";
String subject = "aaaaaaaaaaa"; // 邮件标题
     String body = "bbbbbbbbbbbbbb"; // 邮件内容
     Properties props=System.getProperties();
     props.put("mail.smtp.host", "smtp.qq.com");
     props.put("mail.smtp.auth","true");
    // Session session=Session.getDefaultInstance(props);
     Session session = Session.getDefaultInstance(props,new SimpleAuthenticator(userName, password) );
     SMTPMessage message=new SMTPMessage(session);
     try {
    message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));//收件人
    message.setSubject(subject);
message.setText(body);
message.setFrom(new InternetAddress("[email protected]"));//设置发件人 发件人必须要和Authenticator验证的帐号一致
Transport transport = session.getTransport("smtp");
transport.connect(userName, password);
transport.send(message);
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
     
             
        
}

public static void main(String[] args) {
SendMail.sendMail();
}
}

猜你喜欢

转载自mauersu.iteye.com/blog/1982860