ssl多人多附件多格式邮件发送

本文详细介绍了一种使用JavaMail API发送包含附件的电子邮件的方法。通过配置SMTP服务器、使用SSL加密连接并设置邮件属性,实现了从Java应用程序发送带有多个附件的邮件的功能。文章提供了完整的代码示例,包括如何设置邮件会话、创建邮件、添加附件以及发送邮件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.dfmy.util;

import java.io.File;
import java.security.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
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;
import javax.mail.internet.MimeUtility;
import org.junit.Test;


/**
* javaMail的邮件工具类
*
*/
public class sendEmailUtils {

/**
* 使用加密的方式,利用465端口进行传输邮件,开启ssl
* @param to 收件人邮箱
* @param message 发送的消息
*/
@SuppressWarnings("restriction")
public static void sendEmil(String to, String subject,String message,String html,List<File> files ) {
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//设置邮件会话参数
Properties props = new Properties();
//邮箱的发送服务器地址
props.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
//邮箱发送服务器端口,这里设置为465端口
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
final String username = "echo@luotuowenxueshe.cn";
final String password = "Wxdlt1314";
//获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
//通过会话,得到一个邮件,用于发送
Message msg = new MimeMessage(session);
//设置发件人
msg.setFrom(new InternetAddress("echo@luotuowenxueshe.cn"));
//设置收件人,to为收件人,cc为抄送,bcc为密送
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));

//设置发送的日期
msg.setSentDate(new Date());

//设置邮件主题
msg.setSubject(subject);

//设置邮件消息
// msg.setText(message);

/**/

//整封邮件的MINE消息体
MimeMultipart msgMultipart = new MimeMultipart("mixed");//混合的组合关系
//设置邮件的MINE消息体
msg.setContent(msgMultipart);

//related
MimeMultipart relatedPart = new MimeMultipart("related");

//alternative
MimeMultipart alternativePart = new MimeMultipart("alternative");

//
MimeBodyPart relatedcontent = new MimeBodyPart();
MimeBodyPart alternativecontent = new MimeBodyPart();

//
relatedcontent.setContent(relatedPart);
alternativecontent.setContent(alternativePart);

if (message != null && message!="") {
//纯文本消息
BodyPart textpart = new MimeBodyPart();
textpart.setText(message);
alternativePart.addBodyPart(textpart);
}


if (html != null && html != "") {
//html代码部分
MimeBodyPart htmlPart = new MimeBodyPart();
//html代码
htmlPart.setContent(html,"text/html;charset=utf-8");
alternativePart.addBodyPart(htmlPart);
}

//html中嵌套的图片部分
//MimeBodyPart imgPart = new MimeBodyPart();
//正文添加图片和html代码
//relatedPart.addBodyPart(imgPart);
//图片代码
//imgPart.setHeader("Content-Location", "http://www.luotuowenxueshe.cn/upload/avatar/0/13.jpg");

//附件
// 添加附件的内容
if (null != files && files.size() != 0) {
for (File file : files) {
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentBodyPart.setDataHandler(new DataHandler(source));
//MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
//把附件加入到 MINE消息体中
msgMultipart.addBodyPart(attachmentBodyPart);
}
}

//把内容加入到 MINE消息体中
//relatedPart.addBodyPart(alternativecontent);
msgMultipart.addBodyPart(alternativecontent);

//生成文件邮件
msg.saveChanges();

/**/
//调用Transport的send方法去发送邮件
Transport.send(msg);

} catch (Exception e) {
e.printStackTrace();
}

}

@Test
public void testsend(){

String to ="1334663563@qq.com,18293169616@163.com";
String subject ="测试主题";
String text ="测试文本内容aaa111";
String html ="<span style='color:red'>中文呵呵5464646kl;kd</span> <img src='http://www.luotuowenxueshe.cn/upload/avatar/0/13.jpg'>";
File testFile=new File("D:\\test/123.txt");
File testFileimg=new File("D:\\test/93438.jpg");
File mydoc=new File("D:\\test/mydoc1.doc");

List<File> files=new ArrayList<File>();

files.add(testFile);
files.add(testFileimg);
files.add(mydoc);

sendEmil(to, subject, text,html, files);
}

}

转载于:https://www.cnblogs.com/gwzzayy/p/9794489.html

/* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="380595305@qq.com">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String)it.next(); message.addRecipients(Message.RecipientType.TO, email); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值