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

    技术2022-05-20  42

    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 id URL url = new URL("http://www.zenexity.fr/wp-content/themes/zenexity/images/logo.png"); String cid = email.embed(url, "Zenexity logo"); // set the html message email.setHtmlMsg("<html>Zenexity logo - <img src=/"cid:"+cid+"/"></html>"); // set the alternative message email.setTextMsg("Your email client does not support HTML messages, too bad :(");

    配置文件中关于 SMTP的配置

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

    }

     

    }

     

     


    最新回复(0)