java发送邮件
程序员文章站
2022-06-18 17:16:10
...
1、引入java.mail 包 和 javax.activation包
compile(‘javax.activation:activation:1.1.1’)
compile(‘javax.mail:mail:1.5.0-b01’)
2、直接上代码了
import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.commons.collections.CollectionUtils;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 邮件发送服务
* @author xiongkw
*/
@Component
@Data
public class MailSender {
//邮件服务器地址
@Value("${mailService.host}")
private String host;
//发件人
@Value("${mailService.from}")
private String from;
//如果是腾讯企业邮箱,此处为邮箱密码;如果是qq邮箱、163邮箱等,此处为【授权码】
@Value("${mailService.password}")
private String password;
//加密方式
@Value("${mailService.encryptProtocol}")
private String encryptProtocol;
/**
* 发送纯文本邮件
* @param toAddressList
* @param subject
* @param content
*/
public void sendPlainText(List<String> toAddressList,String subject,String content){
try{
Transport.send(this.buildMessage(toAddressList,subject,content,null));
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 发送带附件的邮件
* @param toAddressList
* @param subject
* @param content
* @param filePathList
*/
public void sendWithAttachMent(List<String> toAddressList,String subject,String content,List<String> filePathList){
try{
Transport.send(this.buildMessage(toAddressList,subject,content,filePathList));
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 构建邮件内容
* @param toAddressList
* @param subject
* @param content
* @param filePathList
* @return
* @throws Exception
*/
private Message buildMessage(List<String> toAddressList,String subject,String content,List<String> filePathList)throws Exception{
// 获取系统属性
Properties props = System.getProperties();
// 设置邮件服务器
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.auth", "true");
// props.setProperty("mail.smtp.port", "587");
if(StringUtils.isBlank(encryptProtocol))encryptProtocol = "ssl";
props.put("mail.smtp."+this.encryptProtocol.toLowerCase()+".enable", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.socketFactory", sf);
// 获取默认的 Session对象。
Session session = Session.getDefaultInstance(props,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(from, password);
}
});
MimeMessage message = new MimeMessage(session);
message.setSubject(subject);
message.setFrom(new InternetAddress(from));
for(String to : toAddressList){
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
}
// 创建多重消息
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
// 消息
messageBodyPart.setContent(content,"text/html;charset=UTF-8");
multipart.addBodyPart(messageBodyPart);
// 附件部分
if(CollectionUtils.isNotEmpty(filePathList)){
for(String filePath : filePathList){
BodyPart filePart = new MimeBodyPart();
DataSource source = new FileDataSource(filePath);
DataHandler dataHandler = new DataHandler(source);
filePart.setDataHandler(dataHandler);
filePart.setFileName(MimeUtility.encodeText(dataHandler.getName()));
multipart.addBodyPart(filePart);
}
}
message.setContent(multipart);
return message;
}
public static void main(String [] args) throws Exception
{
MailSender mailSender = new MailSender();
//腾讯企业邮箱:smtp.exmail.qq.com;qq邮箱:smtp.qq.com;163邮箱: smtp.163.com; office365邮箱:smtp.partner.outlook.cn
mailSender.setHost("smtp.qq.com");
mailSender.setFrom("[email protected]");
//如果是腾讯企业邮箱、office365邮箱,此处为邮箱密码;如果是qq邮箱、163邮箱等,此处为【授权码】
mailSender.setPassword("password");
//加密方式,默认使用ssl ,office365 需要使用starttls
mailSender.setEncryptProtocol("starttls");
//收件人
List<String> toList = new ArrayList<String>(){{add("[email protected]");}};
mailSender.sendPlainText(toList,"发几封邮件给你!","邮件测试");
List<String> filePathList = new ArrayList<>();
filePathList.add("/Users/xiongkw/Downloads/入驻申请驳回率.sql");
filePathList.add("/Users/xiongkw/Downloads/第三方平台店铺服务协议.pdf");
mailSender.sendWithAttachMent(toList,"带附件的邮件","请查看附件",filePathList);
}
}```
上一篇: Linux下安装Maven
下一篇: 如何将jar包打入到本地maven库中