使用javamail 发送邮件

时间:2021-02-28 18:12:13

  废话不多说,直接贴代码:

<!-- maven 依赖 -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

 

package com.example.zgz.demo;

import java.io.File;
import java.util.List;

/**
 * @author zhangguangze
 * @version v1.0
 * @project: zgz
 * @description: 这里描述类的用处
 * @copyright: © 2018
 * @company:
 * @date 2018/5/17 15:02
 */
public class SendEmailVO {
    private String from;
    private String password;
    private String subject;
    private String content;
    private List<String> toArr;
    private List<String> ccArr;
    private List<File> attachArr;

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public List<String> getToArr() {
        return toArr;
    }

    public void setToArr(List<String> toArr) {
        this.toArr = toArr;
    }

    public List<String> getCcArr() {
        return ccArr;
    }

    public void setCcArr(List<String> ccArr) {
        this.ccArr = ccArr;
    }

    public List<File> getAttachArr() {
        return attachArr;
    }

    public void setAttachArr(List<File> attachArr) {
        this.attachArr = attachArr;
    }
}
package com.example.zgz.demo;

import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.util.ArrayList;
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.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 java.io.File;
import java.util.Date;

/**
 * @author zhangguangze
 * @version v1.0
 * @project: zgz
 * @description: 这里描述类的用处
 * @copyright: © 2018
 * @company:
 * @date 2018/5/17 13:56
 */
public class EmailUtil {

    private static String host = "mail.qq.com";
    private static String port = "25";
    private static String userName = "xx@qq.com";
    private static String password = "xxxxx";

    /**
     * 发送邮件
     *
     * @throws Exception
     */
    private static void sendMail(SendEmailVO vo) throws Exception
    {
        Message mailMessage = getMessage(vo);
        MimeMultipart multipart = new MimeMultipart("mixed");

        //设置正文
        BodyPart messageBodyPart = new MimeBodyPart();
        String content = vo.getContent();
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        multipart.addBodyPart(messageBodyPart);

        //设置附件
        MimeBodyPart fileBodyPart;
        if(vo.getAttachArr()!=null && vo.getAttachArr().size()>0){
            for(File f :vo.getAttachArr()){
                fileBodyPart = new MimeBodyPart();
                DataSource fds = new FileDataSource(f);
                fileBodyPart.setDataHandler(new DataHandler(fds));
                fileBodyPart.setFileName(MimeUtility.encodeWord(f.getName()));
                multipart.addBodyPart(fileBodyPart);
            }
        }

        // 设置邮件消息的主要内容
        mailMessage.setContent(multipart);

        // 发送邮件
        Transport.send(mailMessage);
    }

    private static Message getMessage(SendEmailVO vo) throws Exception{
        Properties pro = System.getProperties();
        pro.put("mail.smtp.host", host);
        pro.put("mail.smtp.port", port);
        pro.put("mail.smtp.auth", "true");

        final PasswordAuthentication authentication = new PasswordAuthentication(vo.getFrom(),vo.getPassword());

        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session session = Session.getDefaultInstance(pro,
                new Authenticator()
                {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication()
                    {
                        return authentication;
                    }
                }
        );

        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(session);
        // 设置邮件消息的发送者
        mailMessage.setFrom(new InternetAddress(vo.getFrom()));

        // 接收者
        List<String> toArr = vo.getToArr();
        ArrayList<InternetAddress> toAddArr = new ArrayList<>();
        for(String to : toArr){
            if(StringUtils.isNotBlank(to)){
                toAddArr.add(new InternetAddress(to));
            }
        }
        InternetAddress[] toAdds = toAddArr.toArray(new InternetAddress[toAddArr.size()]);
        mailMessage.setRecipients(Message.RecipientType.TO, toAdds);

        // 抄送
        List<String> ccArr = vo.getCcArr();
        if(ccArr != null && ccArr.size()>0){
            ArrayList<InternetAddress> ccAddArr = new ArrayList<>();
            for(String cc : ccArr){
                if(StringUtils.isNotBlank(cc)) {
                    ccAddArr.add(new InternetAddress(cc));
                }
            }
            if(ccAddArr.size()>0){
                InternetAddress[] ccAdds = ccAddArr.toArray(new InternetAddress[ccAddArr.size()]);
                mailMessage.setRecipients(Message.RecipientType.CC, ccAdds);
            }
        }

        // 设置邮件消息的主题
        mailMessage.setSubject(vo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());

        return mailMessage;
    }

    /**
     * 发送内嵌图片和附件邮件
     *
     * @throws Exception
    public void sendImageAndAttachmentMail() throws Exception
    {
        Properties pro = System.getProperties();
        pro.put("mail.smtp.host", host);
        pro.put("mail.smtp.port", port);
        pro.put("mail.smtp.auth", "true");

        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(pro,
                new Authenticator()
                {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication()
                    {
                        return new PasswordAuthentication(userName, password);
                    }
                });
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 设置邮件消息的发送者
        mailMessage.setFrom(new InternetAddress(userName));
        // 创建邮件的接收者地址,并设置到邮件消息中
        mailMessage.setRecipient(Message.RecipientType.TO,
                new InternetAddress(to));
        // 设置邮件消息的主题
        mailMessage.setSubject("Test Email");
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());

        // 正文
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("我的头像:<img src='cid:headImg'>",
                "text/html;charset=UTF-8");

        // 正文图片
        MimeBodyPart image = new MimeBodyPart();
        image.setDataHandler(
                new DataHandler(new FileDataSource("1_jianggujin.jpg")));
        image.setContentID("headImg");

        // 附件
        MimeBodyPart attach = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("1_jianggujin.jpg"));
        attach.setDataHandler(dh);
        attach.setFileName(MimeUtility.encodeWord(dh.getName()));

        // 描述关系:正文和图片
        MimeMultipart mp1 = new MimeMultipart();
        mp1.addBodyPart(text);
        mp1.addBodyPart(image);
        mp1.setSubType("related");

        // 正文
        MimeBodyPart content = new MimeBodyPart();
        content.setContent(mp1);

        MimeMultipart multipart = new MimeMultipart("mixed");
        multipart.addBodyPart(content);
        multipart.addBodyPart(attach);

        mailMessage.setContent(multipart);
        // 发送邮件
        Transport.send(mailMessage);
    }
     */

    public static void main(String[] args) throws Exception {
        SendEmailVO vo = new SendEmailVO();
        vo.setFrom(userName);
        vo.setPassword(password);
        vo.setSubject("Test");
        vo.setContent("<html><body><div style='font-weight:bold'>Dear All,<br>this is a test email.</div></body></html>");
        List<String> toArr = new ArrayList<>();
        toArr.add("xxxxx@qq.com");
        vo.setToArr(toArr);
        List<String> ccArr = new ArrayList<>();
        ccArr.add("sssss@qq.com");
        vo.setCcArr(ccArr);
        List<File> fileArr = new ArrayList<>();
        fileArr.add(new File("F:\\testpdf\\pdf\\test.txt"));
        vo.setAttachArr(fileArr);
        EmailUtil.sendMail(vo);
    }
}