java freemarker 图片_Java使用freemarker模版发送包含图片邮件

最近要做一个流程发送邮件的事情。发送的对象不一样。邮件内容不一样。使用freemarker 模版来作为邮件发送的模版。

java 发送邮件首先需要导入所需jar包。因为发送邮件中包涵图片所以需要引入文件传输依赖。

maven依赖如下:

org.apache.commons

commons-email

1.2

commons-io

commons-io

2.4

org.freemarker

freemarker

2.3.20

com.us

kulm

2.8.4

commons-fileupload

commons-fileupload

1.3.1

工具类如下

请求数据如下,这个是实用了新浪的邮件服务器;

Host=smtp.sina.com

User=你的账号@sina.com

Pswd=你的密码

Image=D:/DT/upload/image9.jpg(你的图片物理路径)

public class MailUtil {

/** * * 邮件发送工具,默认开启SSL和TSL * *@param fromEmail * 邮件发送人 *@param toEmails * 邮件接收者,支持多个接收者 *@param subject * 标题 *@param message * 信息 *@param host * 邮件发送服务器 *@param port * 端口 *@param username * 用户名 *@param password * 密码 */

public static void sendEmail(String host, String emailUser, String pswd, Set toEmails, String emailImage,

String subject, String htmlText) throws Exception {

Properties props = new Properties();

props.setProperty("mail.transport.protocol", "smtp");

props.setProperty("mail.host", host);

props.setProperty("mail.user", emailUser);

props.setProperty("mail.password", pswd);

props.setProperty("mail.smtp.auth", "true");

Session mailSession = Session.getDefaultInstance(props, null);

mailSession.setDebug(true);

Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);

message.setSubject(subject);

message.setFrom(new InternetAddress(emailUser));

InternetAddress[] Email = new InternetAddress[toEmails.size()];

Iterator it = toEmails.iterator();

for (int i = 0; i < toEmails.size(); i++) {

Email[i] = new InternetAddress(it.next());

}

message.addRecipients(Message.RecipientType.TO, Email);

MimeMultipart multipart = new MimeMultipart("related");

// first part (the html)

BodyPart messageBodyPart = new MimeBodyPart();

messageBodyPart.setContent(htmlText, "text/html;charset=UTF-8");

// add it

multipart.addBodyPart(messageBodyPart);

// second part (the image)

messageBodyPart = new MimeBodyPart();

DataSource fds = new FileDataSource(emailImage);

messageBodyPart.setDataHandler(new DataHandler(fds));

messageBodyPart.setHeader("Content-ID", "");

// add it

multipart.addBodyPart(messageBodyPart);

// put everything together

message.setContent(multipart);

transport.connect(null, emailUser, pswd);

transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));

transport.close();

}

public static String getMailText(FreeMarkerConfigurer freeMarkerConfigurer, String templateName,

Map map) throws Exception {

String htmlText = "";

// 通过指定模板名获取FreeMarker模板实例

Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);

// FreeMarker通过Map传递动态数据

// 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。

htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);

return htmlText;

}

}

使用freemarker 模版首先要配置bean ,spring 中加入配置如下:也可以通过xml 的形式配置。classpath:templates 是模版文件的folder名字。如图

0818b9ca8b590ca3270a3433284dd417.png

@Configuration

public class TemplateConfig {

@Bean

public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {

FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();

factory.setTemplateLoaderPaths("classpath:templates");

factory.setDefaultEncoding("UTF-8");

FreeMarkerConfigurer result = new FreeMarkerConfigurer();

result.setConfiguration(factory.createConfiguration());

return result;

}

}

配置完以后要编写 freemarker模版,简单编写如下“${content}“ 后面调用要传递参数。img src=”cid:image” 是为了对应邮件工具类中对图片的传递。

${content}

接下来就是在service 中调用了:首先要注入FreeMarkerConfigurer

@Autowired

private FreeMarkerConfigurer freeMarkerConfigurer;

//在方法中调用语句如下

Map templateMap = new HashMap();

templateMap.put("content", content);

MailUtil.sendEmail("smtp.sina.com", "你的账号@sina.com","你的密码", "邮件接收者的list集合", "邮件发送图片的路径","邮件的标题",

MailUtil.getMailText(freeMarkerConfigurer, "emailTemp.ftl", templateMap));

toEmails.clear();

getMailText 是获取邮件模版。得到的html 字符串。emailTemp.ftl是模版的名字。templateMap是给模版中传递参数。

上述例子只是邮件发送单图片。下边提供多图片的一个工具类大家自行结合:此类并没有结合模版。只是我的参考资料。大家如果要做多图片也可以参考。

package sendEmail;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class AttchImgMail {

// JavaMail需要Properties来创建一个session对象。它将寻找字符串"mail.smtp.host",属性值就是发送邮件的主机.

public static void main(String[] args) throws Exception {

Properties properties = new Properties();

// properties.put("mail.smtp.host", "mailcas.chinapnr.com");// 设置smtp主机

properties.put("mail.smtp.host", "smtp.163.com");// 设置smtp主机

properties.put("mail.smtp.auth", "true");// 使用smtp身份验证

/* * 在 JavaMail 中,可以通过 extends Authenticator 抽象类,在子类中覆盖父类中的 * getPasswordAuthentication() 方法,就可以实现以不同的方式来进行登录邮箱时的用户身份认证。JavaMail * 中的这种设计是使用了策略模式(Strategy */

MimeMessage message = new MimeMessage(Session.getInstance(properties,

new Authenticator() {

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(//设置发送帐号密码

"帐号", "密码");

}

}));

// 设置邮件的属性

// 设置邮件的发件人

message.setFrom(new InternetAddress("发件人"));

// 设置邮件的收件人 cc表示抄送 bcc 表示暗送

message.setRecipient(Message.RecipientType.TO, new InternetAddress(

"收件人"));

// 设置邮件的主题

message.setSubject("系统自动发送邮件");

// 创建邮件的正文

MimeBodyPart text = new MimeBodyPart();

// setContent(“邮件的正文内容”,”设置邮件内容的编码方式”)

text.setContent("此邮件为系统自动发送",

"text/html;charset=gb2312");

// 点到点的发送

// 一对多发送只要改一个地方如下:

// // 构建一个群发地址数组

// InternetAddress[] adr=new InternetAddress[toMore.length];

// for(int i=0;i

// InternetAddress(toMore[i]); }

// // Message的setRecipients方法支持群发。。注意:setRecipients方法是复数和点 到点不一样

// message.setRecipients(Message.RecipientType.TO,adr);

// 创建图片

MimeBodyPart img = new MimeBodyPart();

/* * JavaMail API不限制信息只为文本,任何形式的信息都可能作茧自缚MimeMessage的一部分. * 除了文本信息,作为文件附件包含在电子邮件信息的一部分是很普遍的. JavaMail * API通过使用DataHandler对象,提供一个允许我们包含非文本BodyPart对象的简便方法. */

DataHandler dh = new DataHandler(new FileDataSource("src//a.jpg"));//图片路径

img.setDataHandler(dh);

// 创建图片的一个表示用于显示在邮件中显示

img.setContentID("a");

MimeBodyPart img2 = new MimeBodyPart();

DataHandler dh2 = new DataHandler(new FileDataSource("src//b.jpg"));//第二张图片路径

img2.setDataHandler(dh2);

img2.setContentID("b");

// 创建附件

// MimeBodyPart attch = new MimeBodyPart();

// DataHandler dh1 = new DataHandler(new FileDataSource("src//b.jpg"));

// attch.setDataHandler(dh1);

// String filename1 = dh1.getName();

// MimeUtility 是一个工具类,encodeText()用于处理附件字,防止中文乱码问题

// attch.setFileName(MimeUtility.encodeText(filename1));

// 关系 正文和图片的

MimeMultipart mm = new MimeMultipart();

mm.addBodyPart(text);

mm.addBodyPart(img);

mm.setSubType("related");// 设置正文与图片之间的关系

// 图班与正文的 body

MimeBodyPart all = new MimeBodyPart();

all.setContent(mm);

// 附件与正文(text 和 img)的关系

MimeMultipart mm2 = new MimeMultipart();

mm2.addBodyPart(all);

mm2.addBodyPart(img2);

mm2.setSubType("mixed");// 设置正文与附件之间的关系

message.setContent(mm2);

message.saveChanges(); // 保存修改

Transport.send(message);// 发送邮件

System.out.println("邮件发送成功");

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Freemarker模板发送邮件,需要进行以下步骤: 1. 导入需要的依赖 在Maven项目中,需要在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> ``` 2. 编写Freemarker模板 比如我们可以编写一个简单的模板,如下: ``` <html> <body> <h1>Hello ${username}!</h1> <p>Here is your message:</p> <p>${message}</p> </body> </html> ``` 在模板中,我们可以使用Freemarker的语法来动态生成HTML内容。 3. 编写Java代码 我们可以编写一个名为`EmailService`的Java类来发送邮件。 首先,我们需要创建一个`VelocityEngine`对象,来加载Freemarker模板: ``` VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.init(); ``` 然后,我们可以使用`VelocityEngine`对象来加载模板文件: ``` Template template = velocityEngine.getTemplate("email-template.vm"); ``` 接下来,我们需要创建一个`VelocityContext`对象,并将模板中需要填充的变量添加到该对象中: ``` VelocityContext context = new VelocityContext(); context.put("username", username); context.put("message", message); ``` 最后,我们可以使用`JavaMail`库来发送邮件: ``` Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(fromEmail, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromEmail)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); message.setSubject(subject); StringWriter writer = new StringWriter(); template.merge(context, writer); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(writer.toString(), "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); ``` 在以上代码中,我们首先创建了一个`Properties`对象来配置邮件服务器的信息。然后,我们创建了一个`Session`对象,并使用`Authenticator`对象来进行SMTP认证。接着,我们创建了一个`MimeMessage`对象,并设置了邮件发送者、接收者和主题。然后,我们将模板生成的HTML内容添加到`MimeBodyPart`对象中,最后将`MimeBodyPart`对象添加到`Multipart`对象中,并将`Multipart`对象设置为邮件的内容。最后,我们使用`Transport`对象的`send`方法来发送邮件。 这就是使用Freemarker模板发送邮件的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值