JAVA发送Email到指定邮箱(163.com/126.com等)
import java.util.Date;
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 javax.mail.internet.MimeMessage;
/*
* 发送电子邮件
* 传入参数
* 参数一:邮件的smtp地址
* 参数二:接收人的邮件地址
* 参数三:邮件的登录用户名
* 参数四:邮件的登录密码
* 参数五:邮件的标题
* 参数六:邮件的内容
* 邮件发送统一采用html格式
*/
public class SentEmail {
String smtpHost = null;
String toaddress = null;
static String userNameTemp = null;
static String pswTemp = null;
String title = null;
private String body = null;
/*
* 构造函数
* 初始化传参
*/
public SentEmail(String smtpHost,String toaddress,String userName,String psw,String title,String body){
this.smtpHost = smtpHost;
this.toaddress = toaddress;
this.userNameTemp = userName;
this.pswTemp = psw;
this.title = title;
this.body = body;
}
public void execSend(){
Properties props = new Properties();
props.put("mail.smtp.host",this.smtpHost);//定义邮件服务器的地址
props.put("mail.smtp.auth", "true");
Session session=
Session.getDefaultInstance(props,
new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userNameTemp, pswTemp);
}
});
MimeMessage message=new MimeMessage(session);
try {
message.setSubject(this.title);//邮件标题
message.setText(this.body);//邮件内容
message.setFrom(new InternetAddress("lyz@126.com"));//发件人的邮件地址,
message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.toaddress));//接收邮件的地址
message.setSentDate(new Date());//邮件发送的时间日期
Transport.send(message);
System.out.println("邮件已发送!");
} catch (MessagingException e) {
System.out.println("发送邮件到:" + this.toaddress + "失败!MessagingException");
}
}
}