前提:需要导入mail.jar
第一步:写好配置文件—email_template.properties, 范例内容如下:
subject=来自会飞的鸟的激活邮件 //这个自己随意
content=恭喜,您已注册成功,请点击这里完成激活。
from= XXXX@163.com //发送到的邮箱,以163为例
host=smtp.163.com
username=XXXX //163邮箱的账号
password=XXXX //163邮箱的密码
第二步:加载配置文件,完成发送功能
Properties prop = new Properties();
try {
prop.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
} catch (IOException e1) {
throw new RuntimeException(e1);
}
String host = prop.getProperty("host");//得到主机名
String name = prop.getProperty("username");//得到登录名
String pass = prop.getProperty("password");//得到登陆密码
createSession(host, name, pass);
String from = prop.getProperty("from");//发件人
String to = user.getEmail();//收件人从前台获取
String subject = prop.getProperty("subject");//主题
//MessageFormat.format方法会把第一个参数中的{0},使用第二个参数来替换
//例如MessageFormat.format("你好{0},你{1}!","张三","去死吧");返回"你好张三,你去死吧"//张三代替了{0}...
//将模板中的占位符{0}替换成了激活码
format(prop.getProperty("content"),user.getActivationCode());//内容
Mail mail = new Mail(from,to,subject,content);
try {
System.out.println("准备发送邮件");
send(session, mail);
System.out.println("已发送邮件");
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}