https://www.cnblogs.com/younldeace/p/5193103.html

最近做个邮件发送功能,要内嵌图片并有附件。

需求很奇怪,图片和附件文件是放在ftp服务器上的,查了下javamail的文档。

添加附件方法如下

MimeBodyPart messageBodyPart=new MimeBodyPart();
DataSource dataSource1=new FileDataSource("d:/xx.doc");
//DataSource dataSource1=new UrlDataSource("url");

  

按照这个api,只能先把ftp文件下载到本地,然后再读,多次一句,还额外增加了读写的成本。为什么这个api不直接提供个二进制流的DataSource呢。

百度了很久也没找到。后来google了一下,马上找到解决方案。

就是ByteArrayDataSource,这是javamail util包里的一个api。

附上完整的内嵌图片, 另发附件的javamail代码。

package com.allianture.core.sendEmail.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Security;
import java.util.Date;
import java.util.Properties; import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
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;
import javax.mail.util.ByteArrayDataSource; import com.allianture.platform.common.api.config.FtpConfig;
import com.allianture.platform.common.api.util.FtpUtils;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility; public class TestMail {
// static int port = 587; static String server = "smtp.exmail.qq.com";// 邮件服务器mail.cpip.net.cn static String from = "AA";// 发送者,显示的发件人名字 static String user = "aa@aa.com";// 发送者邮箱地址 static String password = "aaaa";// 密码 public static void sendEmail() throws UnsupportedEncodingException {
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
props.setProperty("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.store.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
MimeMessage msg = new MimeMessage(session);
String nick=javax.mail.internet.MimeUtility.encodeText("aaa");
msg.setFrom(new InternetAddress(user, nick));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("11@qq.com", false));
msg.setSubject("testest");
msg.setSentDate(new Date()); MimeMultipart multipart = new MimeMultipart("mixed");
// 邮件内容,采用HTML格式
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");
messageBodyPart.setContent(getHtml(), "text/html;charset=GBK"); multipart.addBodyPart(messageBodyPart);
//内嵌图片
messageBodyPart=new MimeBodyPart();
//DataSource dataSource=new FileDataSource("d:/1.png");
URL url;
try {
url = new URL("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png");
DataSource dataSource=new URLDataSource(url);
DataHandler dataHandler=new DataHandler(dataSource);
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setContentID("testi"); multipart.addBodyPart(messageBodyPart); //添加附件
// messageBodyPart=new MimeBodyPart();
// DataSource dataSource1=new FileDataSource("d:/aa.doc");
// dataHandler=new DataHandler(dataSource1);
// messageBodyPart.setDataHandler(dataHandler);
// messageBodyPart.setFileName(MimeUtility.encodeText(dataSource1.getName())); messageBodyPart=new MimeBodyPart();
InputStream is=downloadFtp();
//DataSource dataSource1=new FileDataSource("d:/aa.doc");
DataSource dataSource1=new ByteArrayDataSource(is, "application/png");
dataHandler=new DataHandler(dataSource1);
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setFileName(MimeUtility.encodeText("aa.doc")); multipart.addBodyPart(messageBodyPart);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} msg.setContent(multipart);
msg.saveChanges(); Transport.send(msg); } catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
} public static String getHtml(){
InputStream is;
try {
is = new FileInputStream("d:/测试.html");
byte[] b = new byte[1024];
int size = is.read(b);
return new String(b,0,size);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null; }
public static void main(String args[]) throws UnsupportedEncodingException { sendEmail();// 收件人
//System.out.println(getHtml());
//downloadFtp();
System.out.println("ok");
} public static InputStream downloadFtp(){
try {
FtpUtils ftpUtils = new FtpUtils();
FtpConfig config = new FtpConfig();
config.setEncode("GBK");// 设置编码
config.setServer("101.31.116.513");// 设置服务
config.setPort(21);// 设置端口
config.setUsername("weblogic");// 设置用户名
config.setPassword("weblogic");// 设置密码
config.setLocation("/home/weblogic/ebiz/mailtest");
boolean flag = ftpUtils.connectServer(config);
System.out.println(flag);
System.out.println(ftpUtils.getFileList());
InputStream is=ftpUtils.getFtpClient().retrieveFileStream("aa.doc");
ftpUtils.closeServer();
return is;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; }
}

  

测试.html

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>e</title>
<style>
</style>
</head> <body>
<h1>dusen</h1>
<span style="color:red">this is a test email</span>
<div><img src="cid:testi"></div>
<div><img src="cid:testi2"></div>
</body>
</html>

  

还有一点,qq的企业邮箱要加ssl

javamail: UrlDataSource获取网络文件作为邮件的附件|javamail发送二进制流附件的问题的更多相关文章

  1. javamail发送二进制流附件的问题

    最近做个邮件发送功能,要内嵌图片并有附件. 需求很奇怪,图片和附件文件是放在ftp服务器上的,查了下javamail的文档. 添加附件方法如下 MimeBodyPart messageBodyPart ...

  2. 文件操作总结:关于文本和二进制流(typeText&typeBinary)

    本人能力.精力有限,所言所感都基于自身的实践和有限的阅读.查阅,如有错误,欢迎拍砖,敬请赐教——博客园:钱智慧. 总结: CFile,其自身是不提供缓冲区的(?但CFile又有一个Flush,这一点目 ...

  3. C# 获取网络文件 批量压缩成 文件流 并下载 压缩包

    需要的DLL : ICSharpCode.SharpZipLib.dll JS部分 //下载所有文件的 压缩包 function DownAllFile() { //zip文件名 var zipNam ...

  4. Linux网络中接收 "二进制" 流的那些事 --- 就recv的返回值和strlen库函数进行对话

    1.    前言 很多朋友在做网络编程开发的时候可能都遇到这样的问题,在进行接收二进制流的数据的时候,使用strlen库函数来得到 二进制数据长度的时候并不准确.为什么呢??首先,使用strlen进行 ...

  5. php从数据库中取二进制流文件转换为图片,图片以二进制流存入数据库实现

    php从数据库中取二进制流文件转换为图片,图片以二进制流存入数据库实现 function data_uri($contents, $mime) { $base64 = base64_encode($c ...

  6. 19、文件上传与下载/JavaMail邮件开发

    回顾: 一. 监听器 生命周期监听器 ServletRequestListener HttpSessionListener ServletContextListener 属性监听器 ServletRe ...

  7. javamail模拟邮箱功能获取邮件内容-中级实战篇【内容|附件下载方法】(javamail API电子邮件实例)

    引言: JavaMail jar包下载地址:http://java.sun.com/products/javamail/downloads/index.html 此篇是紧随上篇文章而封装出来的,阅读本 ...

  8. 使用NSURLSession获取网络数据和下载文件

    使用NSURLSession获取网络数据 使用NSURLSession下载文件

  9. 基于javaMail的邮件发送--excel作为附件

    基于JavaMail的Java邮件发送 Author xiuhong.chen@hand-china.com Desc 简单邮件发送 Date 2017/12/8 项目中需要根据物料资质的状况实时给用 ...

随机推荐

  1. WIP*更新生产批详细信息行产品配料

    DECLARE l_batch_header_rec gme_batch_header%ROWTYPE; l_material_detail_rec gme_material_details%ROWT ...

  2. 神奇的print

    一:多看看 1. #大小写转换 ,有大写的 全转化为大写 s = 'fds Kkg' print(s.swapcase()) #下划线等各种插入 s = 'fdsfkg' print('_'.join ...

  3. Xshell连接虚拟机文档教程

    1打开VirtualBox 2 找到导入的虚拟机 3右键虚拟机 启动 4 等待加载 5 加载的时候,打开xshell 6 7 填写框住的内容 名称: 自己取 主机: 127.0.0.1  固定内容 端 ...

  4. Gym102028G Shortest Paths on Random Forests 生成函数、多项式Exp

    传送门 神仙题-- 考虑计算三个部分:1.\(n\)个点的森林的数量,这个是期望的分母:2.\(n\)个点的所有森林中存在最短路的点对的最短路径长度之和:3.\(n\)个点的所有路径中存在最短路的点对 ...

  5. 监听EF执行的sql语句及状态

    1.监听EF执行sql的方式 db.Database.Log += c => Console.WriteLine($"sql:{c}"); SQL Server Profil ...

  6. tcp协议close_wait与time_wait状态含义

    题目描述 1.什么是三次握手,四次挥手?为什么分别要三次与四次? 2.tcp协议中,close_wait与time_wait状态分别代表什么含义,为什么要设计这两种状态,解决了什么问题? 3.time ...

  7. OS UIButton之UIButtonType详解-转

    我做了一个关于UIButtonType的Demo,效果如下图: UIButtonType各个类型的解释: typedef NS_ENUM(NSInteger, UIButtonType) { UIBu ...

  8. php验证码案例

    <?php header('Content-type:image/jpeg'); $img=imagecreatetruecolor(120,40); // 背景颜色 $bg_color=ima ...

  9. 解决mysql跟php不在同一台机器上,编译安装php服务报错问题:configure: error: Cannot find MySQL header files under /application/mysql.

    在编译安装php服务时报错: configure: error: Cannot find MySQL header files under /application/mysql. Note that ...

  10. 安装sqlite3

    说明 当前操作在root用户下执行 1.安装编译工具 yum -y groupinstall "Development tools" yum -y install zlib-dev ...