play framework学习笔记之 发送 e-mail

来源:互联网 发布:linux vim颜色主题 编辑:程序博客网 时间:2024/04/28 19:28

Sending e-mail

使用的是 Apache Commons Email 


A simple e-mail:简单的邮件发送

SimpleEmail email = new SimpleEmail();email.setFrom("sender@zenexity.fr");email.addTo("recipient@zenexity.fr");email.setSubject("subject");email.setMsg("Message");Mail.send(email); 

An HTML e-mail: 一个HTML页面电子邮件的发送

HtmlEmail email = new HtmlEmail();email.addTo("info@lunatech.com");email.setFrom(sender@lunatech.com", "Nicolas");email.setSubject("Test email with inline image");// embed the image and get the content idURL url = new URL("http://www.zenexity.fr/wp-content/themes/zenexity/images/logo.png");String cid = email.embed(url, "Zenexity logo");                                           // set the html messageemail.setHtmlMsg("<html>Zenexity logo - <img src=/"cid:"+cid+"/"></html>");// set the alternative messageemail.setTextMsg("Your email client does not support HTML messages, too bad :(");     

配置文件中关于 SMTP的配置

# Default is to use a mock Mailermail.smtp=mock //此时,将不会实际发送邮件而是,模拟发送并打印信息# Or, specify mail host configuration //帮我们提供邮件发送服务的SMTP服务器的一些配置mail.smtp.host=smtp.qq.com mail.smtp.user=554943871mail.smtp.pass=mail.smtp.channel=sslmail.debug=true

先创建包notifiers

然后是例子代码

package notifiers;

import play.*;

import play.mvc.*;

import java.util.*;

public class Mails extends Mailer {


public static void welcome(User user) {

setSubject("Welcome %s", user.name);

addRecipient(user.email);

setFrom("Me <me@me.com>");

EmailAttachment attachment = new EmailAttachment();

attachment.setDescription("A pdf document");

attachment.setPath(Play.getFile("rules.pdf").getPath());

addAttachment(attachment);

send(user);

}


public static void lostPassword(User user) {

String newpassword = user.password;

setFrom("Robot <robot@thecompany.com>");                   //注意此处,需要和你的SMTP的HOST账户对应的

setSubject("Your password has been reset");

addRecipient(user.email);

send(user, newpassword);                                           //send相当于render,他会去渲染对应的HTML并发送

}

 

}

 

 

原创粉丝点击