package test;
import java.io.UnsupportedEncodingException;
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 SendMail {
public static void main(String[] args) {
/*
* 常用邮箱SMTP服务器地址大全
* 阿里云邮箱(mail.aliyun.com):SMTP服务器地址:smtp.aliyun.com(SSL加密端口:465;非加密端口:25)
* 谷歌邮箱(google.com):SMTP服务器地址:smtp.gmail.com(SSL启用端口:587)
* 新浪邮箱(sina.com):SMTP服务器地址:smtp.sina.com.cn(端口:25)
* 网易邮箱(163.com):SMTP服务器地址:smtp.163.com(端口:25)
* 126邮箱:SMTP服务器地址:smtp.126.com(端口:25)
* 雅虎中国(yahoo.com.cn):SMTP服务器地址:smtp.mail.yahoo.com.cn(端口:587)
* 雅虎邮箱POP3的SSL不启用端口为110,POP3的SSL启用端口995;SMTP的SSL不启用端口为25,SMTP的SSL启用端口为465
* Foxmail邮箱(foxmail.com):SMTP服务器地址:SMTP.foxmail.com(端口:25)
* QQ邮箱(mail.qq.com):SMTP服务器地址:smtp.qq.com(端口:25) SMTP服务器需要身份验证
* 搜狐邮箱(sohu.com):SMTP服务器地址:smtp.sohu.com(端口:25)
* 移动139邮箱: SMTP服务器地址:SMTP.139.com(端口:25)
* 中华网邮箱(china.com): SMTP服务器地址:smtp.china.com(端口:25)
*/
sendmail("邮箱", "密码", "收信人", "smtp.163.com", "25", "test", "没有正文");
}
/**
* @author XiWood
* @param user
* 用户名
* @param password
* 密码
* @param addressee
* 收信人邮件地址
* @param host
* 发信邮件服务器
* @param port
* 端口
* @param headline
* 邮件标题
* @param text
* 邮件正文
*/
public static void sendmail(final String user, final String password, String addressee, String host, String port,
String headline, String text) {
Properties properties = System.getProperties(); // 获取系统属性
properties.setProperty("mail.smtp.host", host); // 设置邮件服务器
properties.setProperty("mail.smtp.port", port); // 端口号 //设置邮件端口
properties.setProperty("mail.transport.protocol", "smtp");// 必须选择协议
properties.setProperty("mail.smtp.auth", "true");// 设置邮件是否验证
properties.setProperty("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接,由于SSL加密连接容易延迟
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
};
Session session = Session.getInstance(properties, auth);
session.setDebug(true);// 设置是否显示debug信息 true 会在控制台显示相关信息
Message message = new MimeMessage(session);
try {
String nick = "";
try {
nick = javax.mail.internet.MimeUtility.encodeText("自定义发送人名称"); // 设置发送人的自定义名称
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
message.setFrom(new InternetAddress(nick + "<" + user + ">"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(addressee));// 设置收件人
message.setSubject(headline);// 设置邮件标题
message.setContent(text, "text/html;charset=utf-8");// 设置正文编码格式
Transport.send(message);// 发送邮件
System.out.println("Sent message successfully....from runoob.com----邮件已发送s");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}