java发送邮件代码
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.unicloud.uplus.client.oss.OSSClient;
import com.unicloud.uplus.core.protocol.TransferContext;
import com.unicloud.uplus.di.data.trans.steps.custom.mail.Attachment;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MimetypesFileTypeMap;
import javax.annotation.PostConstruct;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
/**
* @Author wangjinpeng
* @Description
* @Date 2021/7/9
* @Version 1.0
*/
@Component
public class MailUtil {
private static Logger logger = LoggerFactory.getLogger(MailUtil.class);
@Autowired
private Environment env;
private static String host = "";
private static String user = "";
private static String pwd = "";
private static String authCode = "";
private static String from = "";
@PostConstruct
public void config() {
host = env.getProperty("mail.host");
user = env.getProperty("mail.user");
pwd = env.getProperty("mail.pwd");
authCode = env.getProperty("mail.authCode");
from = env.getProperty("mail.from");
}
/**
* 后加的防止题目过长并且进行全局定义
*/
static {
System.setProperty("mail.mime.splitlongparameters", "false");
System.setProperty("mail.mime.charset", "UTF-8");
}
public static void send(String to,String cc, String subject, String content, List<Attachment> attachmentList){
Properties props = new Properties();
// 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
props.put("mail.smtp.host", host);
// 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
props.put("mail.smtp.auth", "true");
// 用刚刚设置好的props对象构建一个session
Session session = Session.getDefaultInstance(props);
// 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使
// 用(你可以在控制台(console)上看到发送邮件的过程)
session.setDebug(true);
// 用session为参数定义消息对象
MimeMessage message = new MimeMessage(session);
try {
// 加载发件人地址
message.setFrom(new InternetAddress(from));
// 加载收件人地址
List<String> toList = Arrays.asList(to.split(","));
if(CollectionUtils.isNotEmpty(toList)){
for(String s : toList){
message.addRecipient(Message.RecipientType.TO, new InternetAddress(s));
}
}
// 加载抄送地址
List<String> ccList = Arrays.asList(cc.split(","));
if(CollectionUtils.isNotEmpty(ccList)){
for(String s : ccList){
message.addRecipient(Message.RecipientType.CC, new InternetAddress(s));
}
}
// 加载标题
message.setSubject(subject);
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 设置邮件的文本内容
BodyPart contentPart = new MimeBodyPart();
contentPart.setText(content);
multipart.addBodyPart(contentPart);
List<File> fileList = new ArrayList<>();
// 添加附件
if(CollectionUtils.isNotEmpty(attachmentList)){
BodyPart messageBodyPart = null;
for (Attachment attachment : attachmentList){
messageBodyPart = new MimeBodyPart();
String fileId = attachment.getUri().substring(attachment.getUri().lastIndexOf("/")+1, attachment.getUri().length());
String filePath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator");
File file = OSSClient.download(fileId,filePath);
fileList.add(file);
String fileName = file.getName();
// String contentType = new MimetypesFileTypeMap().getContentType(file);
// DataSource source = new ByteArrayDataSource(new ByteArrayInputStream(OSSClient.download(fileId)),contentType);
DataHandler dataHandler = new DataHandler(new FileDataSource(file));
// 添加附件的内容
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setFileName(MimeUtility.encodeText(fileName));
multipart.addBodyPart(messageBodyPart);
}
}
// 将multipart对象放到message中
message.setContent(multipart);
// 保存邮件
message.saveChanges();
// 发送邮件
Transport transport = session.getTransport("smtp");
// 连接服务器的邮箱
transport.connect(host, user, authCode);
// 把邮件发送出去
transport.sendMessage(message, message.getAllRecipients());
transport.close();
if(CollectionUtils.isNotEmpty(fileList)){
fileList.forEach((file) -> {
file.delete();
});
}
} catch (Exception e) {
e.printStackTrace();
logger.error("发送邮件失败!",e);
}
}
}