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