最近要做一个流程发送邮件的事情。发送的对象不一样。邮件内容不一样。使用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名字。如图
@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("邮件发送成功");
}
}