邮件发送
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;
public class HelloJMail {
public static void sendMail() {
String host = "smtp.163.com"; // 指定的smtp服务器
String from = "hwp6012@163.com"; // 邮件发送人的邮件地址
String to = "hwp6012@sina.com"; // 邮件接收人的邮件地址
final String username = "****************"; //发件人的邮件帐户
final String password = "**********"; //发件人的邮件密码
// 创建Properties 对象
Properties props = System.getProperties();
// 添加smtp服务器属性
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
// 创建邮件会话
Session session = Session.getDefaultInstance(props, new Authenticator(){
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 定义邮件信息
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject("HelloWorld JavaMail");
message.setText("Welcome to JavaMail World!");
// 发送消息
//session.getTransport("smtp").send(message); //也可以这样创建Transport对象
Transport.send(message);
System.out.println("发送成功!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
HelloJMail.sendMail();
}
- }
上一篇: log4j配置