首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

javaMail发邮件 容易小例子

2013-12-06 
javaMail发邮件 简单小例子源:http://my.oschina.net/u/865478/blog/94154评:package com.mailimport jav

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 = "xxxx@qq.com";
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("2222222@qq.com"));//收件人
    message.setSubject(subject);
message.setText(body);
message.setFrom(new InternetAddress("523199766@qq.com"));//设置发件人 发件人必须要和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();
}
}

热点排行