package com.mail;
import javax.mail.AuthenticationFailedException;
import javax.mail.internet.*;
import javax.mail.*;
import java.rmi.RemoteException;
import java.util.*;
public class MailSender {
public static String SMTP_HOST = "smtp.sina.com.cn";
public static String SMTP_USER = "lzy860515";
public static String SMTP_PASSWORD = "liuzhiyuan860515";
public static String SMTP_AUTH = "true";
public static void sendMail(String toAddr, String subject, String body,
String fromAddr) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.auth", SMTP_AUTH);// 同时通过验证
Session session;
if ("true".equals(SMTP_AUTH)) {
// smtp服务器需要验证,用MyAuthertiactor来创建mail session
MyAuthenticator myauth = new MyAuthenticator(SMTP_USER,
SMTP_PASSWORD);
session = Session.getInstance(props, myauth);
} else {
session = Session.getDefaultInstance(props, null);
}
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromAddr));
InternetAddress[] tos = InternetAddress.parse(toAddr);
msg.setRecipients(Message.RecipientType.TO, tos);
msg.setSubject(subject);
msg.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(SMTP_HOST, 26, SMTP_USER, SMTP_PASSWORD);// 以smtp方式登录邮箱
Transport.send(msg);
transport.close();
System.out.println("Mail is Sent");
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String args[]) {
sendMail("lzy860515@sina.com", "测试", "测试内容\n sunny", "lzy860515@sina.com");
System.out.println("发送成功!");
}
}