import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
private static String hostName;// 邮件服务器
private static String from;// 发送邮箱地址
private static String userName;// 用户名
private static String password;// 密码
private static String to;// 发送给邮箱地址
private static String adminName;//邮件显示的名字
static {
/**
* 从配置文件获取邮件服务器,发送邮箱地址,用户名和密码
*/
Properties pro = new Properties();
try {
pro.load(Mail.class.getClassLoader().getResourceAsStream(
"email.properties"));
hostName = pro.getProperty("hostName");// 接受邮件服务器地址
from = pro.getProperty("from");// 接受发件人的地址
userName = pro.getProperty("userName");// 发件人用户名
password = pro.getProperty("password");// 发件人密码
to = pro.getProperty("to");// 发件人密码
adminName = pro.getProperty("adminName");// 发件人密码
} catch (Exception e) {
e.printStackTrace();
}
}
// 发送邮件的帐号和密码
private String mail_head_name = "this is head of this mail";
private String mail_head_value = "this is head of this mail";
public void sendMail(String mail_subject,String mail_body) throws SendFailedException {
try {
// 发送邮件的props文件
Properties props = new Properties();
// 初始化props
props.put("mail.smtp.host", hostName);
props.put("mail.smtp.auth", "true");
System.out.println(props);
// 进行邮件服务用户认证
Authenticator auth = new MyEmailAutherticator(userName, password);
// 创建session,和邮件服务器进行通讯
Session session = Session.getDefaultInstance(props, auth);
// 创建mime类型邮件
MimeMessage message = new MimeMessage(session);
// 设置邮件格式
message.setContent("Hello", "text/html;charset=utf-8");
// 设置主题
message.setSubject(mail_subject);
// 设置邮件内容
message.setText(mail_body);
// 设置邮件标题
message.setHeader(mail_head_name, mail_head_value);
message.setSentDate(new Date());// 设置邮件发送时期
Address address = new InternetAddress(from, adminName);
// 设置邮件发送者的地址
message.setFrom(address);
// ======单发邮件======
// 设置邮件接收者的地址
Address toaddress = new InternetAddress(to);
// 设置收件人
message.addRecipient(Message.RecipientType.TO, toaddress);
System.out.println(message);
// 发送邮件
Transport.send(message);
System.out.println("Send Mail Ok!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Mail m = new Mail();
try {
m.sendMail("消息服务器提醒","消息服务器内存剩下10M");
} catch (Exception e) {
}
}
}