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

本文介绍如何使用 Apache Commons Email 库发送简单邮件及HTML邮件,并附带邮件附件及内联图片。提供了配置SMTP服务器的方法及具体示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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并发送

}

 

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值