javamail 附件以及正文加图片
直接上代码
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties; import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource; import org.apache.commons.httpclient.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service; import com.cdp.api.onboarding.onboardingenum.AttachmentTypeEnum; @Service
public class MailService {
@Value("${ALIDM_SMTP_AUTH}")
private String ALIDM_SMTP_AUTH; @Value("${ALIDM_SMTP_HOST}")
private String ALIDM_SMTP_HOST; @Value("${ALIDM_SMTP_PORT}")
private String ALIDM_SMTP_PORT; @Value("${ALIDM_SMTP_MAIL_USER}")
private String ALIDM_SMTP_MAIL_USER; @Value("${ALIDM_SMTP_MAIL_PASSWORD}")
private String ALIDM_SMTP_MAIL_PASSWORD; @Value("${ALIDM_SMTP_MAIL_FROM}")
private String ALIDM_SMTP_MAIL_FROM; @Value("${ALIDM_SMTP_MAIL_FROM_PERSONAL}")
private String ALIDM_SMTP_MAIL_FROM_PERSONAL; @Value("${ALIDM_SMTP_MAIL_FROM_CHARSET}")
private String ALIDM_SMTP_MAIL_FROM_CHARSET; @Value("${ALIDM_SMTP_MAIL_REPLY}")
private String ALIDM_SMTP_MAIL_REPLY; @Value("${QRCODEPICTUREURL}")
private String ORCODEPATH; @Autowired
private ResourceLoader resourceLoader; /**
* 阿里云smtp邮件服务
*
* @param mailTo
* @param mailSubject
* @param mailText
* @param list
* @throws MessagingException
* @throws HttpException
* @throws IOException
*/
public boolean sendMail(String mailTo, String mailSubject, String mailText)
throws Exception {
return sendMail(mailTo, mailSubject, mailText, null);
} public boolean sendMail(String mailTo, String mailSubject, String mailText,
List<Map<Integer, InputStream>> list) throws Exception {
boolean flag = false; // 配置发送邮件的环境属性
final Properties props = new Properties();
// 表示SMTP发送邮件,需要进行身份验证
props.put("mail.smtp.auth", ALIDM_SMTP_AUTH);
props.put("mail.smtp.host", ALIDM_SMTP_HOST);
props.put("mail.smtp.port", ALIDM_SMTP_PORT);
// 如果使用ssl,则去掉使用25端口的配置,进行如下配置,
// props.put("mail.smtp.socketFactory.class",
// "javax.net.ssl.SSLSocketFactory");
// props.put("mail.smtp.socketFactory.port", "465");
// props.put("mail.smtp.port", "465");
// 发件人的账号
props.put("mail.user", ALIDM_SMTP_MAIL_USER);
// 访问SMTP服务时需要提供的密码
props.put("mail.password", ALIDM_SMTP_MAIL_PASSWORD);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// mailSession.setDebug(true);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
try {
// 设置发件人
InternetAddress from = new InternetAddress(ALIDM_SMTP_MAIL_FROM,
ALIDM_SMTP_MAIL_FROM_PERSONAL, ALIDM_SMTP_MAIL_FROM_CHARSET);
message.setFrom(from);
Address[] a = new Address[1];
a[0] = new InternetAddress(ALIDM_SMTP_MAIL_REPLY);
message.setReplyTo(a);
// 设置收件人
InternetAddress to = new InternetAddress(mailTo);
message.setRecipient(MimeMessage.RecipientType.TO, to);
// 设置邮件标题
message.setSubject(mailSubject);
// 设置邮件的内容体
MimeMultipart mp = new MimeMultipart("related");
MimeBodyPart mbpContent = new MimeBodyPart();
// 判断模版是否要加二维码图片
if (mailText.contains("${MAIL_PHOTO}")) {
mailText = mailText
.replace("${MAIL_PHOTO}",
"<img src=\"cid:image\" width='254' height='254' border='0'>");
mbpContent.setContent(mailText, "text/html; charset=utf-8");
mp.addBodyPart(mbpContent);
InputStream ins = resourceLoader.getResource(ORCODEPATH).getInputStream();
DataSource dataSource4 = new ByteArrayDataSource(ins,
"image/jpeg");
MimeBodyPart image = new MimeBodyPart();
DataHandler dataHandler4 = new DataHandler(dataSource4);
image.setDataHandler(dataHandler4);
image.setHeader("Content-ID", "image");
image.setFileName(dataHandler4.getName());
mp.addBodyPart(image);
ins.close();
} else {
mbpContent.setContent(mailText, "text/html; charset=utf-8");
mp.addBodyPart(mbpContent);
}
/* 往邮件中添加附件 */
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
Map<Integer, InputStream> map = list.get(i); //这里取了map的key值
Iterator<Integer> iter = map.keySet().iterator();
while (iter.hasNext()) {
Integer key = Integer.parseInt(String.valueOf(iter
.next()));
InputStream ins = map.get(key);
//这里加了个枚举
switch (AttachmentTypeEnum.getByValue(key)) {
case PNGJPG:
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.removeHeader("Content-Type");
messageBodyPart
.removeHeader("Content-Transfer-Encoding");
messageBodyPart.addHeader("Content-Type",
"text/html; charset=gbk");
messageBodyPart.addHeader(
"Content-Transfer-Encoding", "base64");
DataSource dataSource1 = new ByteArrayDataSource(
ins, "application/png");
DataHandler dataHandler1 = new DataHandler(
dataSource1);
messageBodyPart.setDataHandler(dataHandler1);
messageBodyPart.setFileName(MimeUtility
.encodeText("附件.jpg"));
mp.addBodyPart(messageBodyPart);
ins.close();
break;
case WORD:
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.removeHeader("Content-Type");
messageBodyPart2
.removeHeader("Content-Transfer-Encoding");
messageBodyPart2.addHeader("Content-Type",
"text/html; charset=gbk");
messageBodyPart2.addHeader(
"Content-Transfer-Encoding", "base64");
DataSource dataSource2 = new ByteArrayDataSource(
ins, "application/docx");
DataHandler dataHandler2 = new DataHandler(
dataSource2);
messageBodyPart2.setDataHandler(dataHandler2);
messageBodyPart2.setFileName(MimeUtility
.encodeText("附件.docx"));
mp.addBodyPart(messageBodyPart2);
ins.close();
break;
case EXCEL:
MimeBodyPart messageBodyPart3 = new MimeBodyPart();
messageBodyPart3.removeHeader("Content-Type");
messageBodyPart3
.removeHeader("Content-Transfer-Encoding");
messageBodyPart3.addHeader("Content-Type",
"text/html; charset=gbk");
messageBodyPart3.addHeader(
"Content-Transfer-Encoding", "base64");
DataSource dataSource3 = new ByteArrayDataSource(
ins, "application/xlsx");
DataHandler dataHandler3 = new DataHandler(
dataSource3);
messageBodyPart3.setDataHandler(dataHandler3);
messageBodyPart3.setFileName(MimeUtility
.encodeText("附件.xlsx"));
mp.addBodyPart(messageBodyPart3);
ins.close();
break;
case MAILPHOTO:
MimeBodyPart image = new MimeBodyPart();
DataSource dataSource4 = new ByteArrayDataSource(
ins, "image/jpeg");
DataHandler dataHandler4 = new DataHandler(
dataSource4);
image.setDataHandler(dataHandler4);
image.setHeader("Content-ID", "a00000002");
image.setFileName(dataHandler4.getName());
mp.addBodyPart(image);
ins.close();
break;
}
}
} }
message.setContent(mp);
message.setSentDate(new Date());
// 发送邮件
Transport.send(message); flag = true;
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} return flag;
}
}
有时在想 一直使用spring感觉会让自己越来越笨,各种写好的注解真的很方便啊
javamail 附件以及正文加图片的更多相关文章
- 使用C#发送正文带图片邮件
最近有个地方用到正文带图片的邮件发送功能,由于发送邮件调用的是web service,要求正文必须是string,而接收方要能看到图片,还不能单纯的添加一个图片地址链接,查阅了很多资料,基本上都是从头 ...
- (二)JavaMail创建包含内嵌图片的邮件
链接:https://blog.csdn.net/qq_41151659/article/details/96475739 代码如下: import com.sun.mail.util.MailSSL ...
- 帝国cms发布信息时替换正文IMG图片标签里的ALT内容
帝国cms发布信息时替换正文IMG图片标签里的ALT内容 在 e/class/userfun.php 里面增加 //替换正文IMG里的ALT内容 function user_imgalt($mid,$ ...
- Delphi TreeView – 自动给标题上加图片
Delphi TreeView – 自动给标题上加图片 当处理完TreeView控件树形结构的数据后,根据不同的树形节点Level,加上不同的图片. 图片的ImageList已经放置好,并且TreeV ...
- PHP的图片处理类(缩放、加图片水印和剪裁)
<!--test.php文件内容--> <?php //包含这个类image.class.php include "image.class.php"; $img ...
- 使用JavaMail发送邮件-从FTP读取图片并添加到邮件正文发送
业务分析: 最近工作需要,需要从FTP读取图片内容,添加到邮件正文发送.发送邮件正文,添加附件采用Spring的MimeMessageHelper对象来完成,添加图片也将采用MimeMessageHe ...
- Thinkphp 3.0版本上传文件加图片缩略图实例解析
先看html加个表单,注意这里的action 路径要选 对. <div> <form action="__URL__/add_img" enctype=" ...
- 循序渐进VUE+Element 前端应用开发(23)--- 基于ABP实现前后端的附件上传,图片或者附件展示管理
在我们一般系统中,往往都会涉及到附件的处理,有时候附件是图片文件,有时候是Excel.Word等文件,一般也就是可以分为图片附件和其他附件了,图片附件可以进行裁剪管理.多个图片上传管理,及图片预览操作 ...
- Python批量创建word文档(2)- 加图片和表格
Python创建word文档,任务要求:小杨在一家公司上班,每天都需要给不同的客户发送word文档,以告知客户每日黄金价格.要求在文档开始处给出banner条,价格日期等用表格表示.最后贴上自己的联系 ...
随机推荐
- HNUSTOJ-1521 塔防游戏
1521: 塔防游戏 时间限制: 1 Sec 内存限制: 128 MB提交: 117 解决: 38[提交][状态][讨论版] 题目描述 小明最近迷上了塔防游戏,塔防游戏的规则就是在地图上建炮塔,用 ...
- 洛谷 - P1346 - 电车 - Dijkstra/01BFS
https://www.luogu.org/problem/P1346 使用最短路之前居然忘记清空了. #include<bits/stdc++.h> using namespace st ...
- Views的补充
views的补充 请求头一般与请求内容用/r/n/r/n隔开 请求头包含的内容 request.Meta(...) 一般在下面几种方法里面取不到的东西需要去原生的头里面去取,比如用户的终端类型 req ...
- sublime text 3基本参数设置及插件使用
sublime text 3常用基本设置,包括插件,字体等一些配置.写个随笔,备忘. soda主题:特别喜欢: 插件:Color Highlighter输入颜色时,可以看到颜色. 在Color Hig ...
- android studio配置模拟器
配置模拟器在Android开发中,肯定是要写好代码看结果的,如果使用as中自带的模拟器太low,启动速度又慢,网上有很多教程推荐使用genymotion模拟器的,可是如果是新手我建议选择更好入门的第三 ...
- Django之modles 多对多创建第三张表
一.第一种:纯自动创建第三张表 纯自动 class Book(models.Model): title = models.CharField(max_length=32) price = models ...
- Qt带参数的信号和槽
在Qt的开发过程中,信号带参数是很常见的,在使用带参数的信号槽时,有以下几点需要注意. 当信号和槽函数的参数数量相同时,它们的参数类型要完全一致. 信号和槽函数的声明: signals: void i ...
- 移动端适配 rem
前置知识: 物理像素(physical pixel,device pixel) 物理像素(设备像素),显示设备中一个最微小的物理部件.每个像素可以根据操作系统设置自己的颜色和亮度. 设备独立像素(de ...
- 错误:非法字符:“\ufeff”
导入开源的项目的时候,你可以碰到以上的编码问题,这一般这个项目是用eclipse开发的.主要原因是: Eclipse可以自动把UTF-8+BOM文件转为普通的UTF-8文件,但Android ...
- java实现一个简单的计数器
package com.fengunion.sf; import org.junit.platform.commons.util.StringUtils; import java.util.HashM ...