package cn.sun.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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class JavaMail {
public static void main(String[] args) throws AddressException,
MessagingException {
String to = "from@163.com";
String from = "to@163.com";
Properties props = new Properties();
Session sendMailSession;
// Store store;
Transport transport;
// String usr = "***";// 这里填写你发信者的邮箱地址
// String pwd = "***";// 这里填写你发信者的邮箱密码
props.put("mail.smtp.host", "smtp.163.com"); // 这里填写你发信者的SMTP主机,如:smtp.sohu.com
// props.put("mail.smtp.user", usr);
// props.put("mail.smtp.password", pwd);
props.put("mail.smtp.auth", "true");
sendMailSession = Session.getInstance(props, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("from#163.com", "***");
}// 这里填写你发信者的邮箱地址和密码
});// 如果你的邮箱是SMTP验证的,就得这么写。否则会报错。Session.getInstance(props)这个方法是针对SMTP不要求验证的,我的邮箱要验证,所以得这么写。
Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom(new InternetAddress(from));
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(
to));
newMessage.setSubject("javamail test");
newMessage.setSentDate(new Date());
newMessage
.setText("javamail testjavamail testjavamail testjavamail testjavamail test");
transport = sendMailSession.getTransport("smtp");
transport.send(newMessage);
}
}
以前写的javamail例子
最新推荐文章于 2023-07-08 23:55:47 发布