java发送邮件

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("xxx@qq.com");
        //如果是腾讯企业邮箱、office365邮箱,此处为邮箱密码;如果是qq邮箱、163邮箱等,此处为【授权码】
        mailSender.setPassword("password");
        //加密方式,默认使用ssl  ,office365 需要使用starttls
        mailSender.setEncryptProtocol("starttls");

        //收件人
        List<String> toList = new ArrayList<String>(){{add("xxxx@qq.com");}};

        mailSender.sendPlainText(toList,"发几封邮件给你!","邮件测试");

        List<String> filePathList = new ArrayList<>();
        filePathList.add("/Users/xiongkw/Downloads/入驻申请驳回率.sql");
        filePathList.add("/Users/xiongkw/Downloads/第三方平台店铺服务协议.pdf");
        mailSender.sendWithAttachMent(toList,"带附件的邮件","请查看附件",filePathList);
    }
}```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值