java mail发送email

一、常见错误:

有一点一定要注意:就是一般的邮件服务器都会需要这样或者那样的验证,所以验证信息是必不可少的,体现在创建session的时候第二个参数

用户名密码或授权码形式的认证

重写Authenticator中的 getPasswordAuthentication 方法,把发送服务器用户密码传入,再生成session

Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mail.getFrom(), mail.getPassword());
            }
        };
Session session = Session.getInstance(properties,auth);

 

二、pom依赖

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

三、实体类

package cn.pkulaw.fblx.util.email;

/**
 * @Author: WXM
 * @Description:
 * @Date: create in 2021/2/1 15:13
 */

public class MailEntity {

    //发送方
    private String from;
    //接受方
    private String to;
    //邮件服务器
    private String addr;
    //授权码(授权码验证时需要)
    private String auth;
    //发送服务器端口号(非必须)
    private Integer port;


    //主题
    private String subject;
    //文本内容
    private String text;
    //附件路径
    private String filePath;
    //附件文件名
    private String fileName;
    //附件文件类型
    private String fileType;
    //附件文件
    private byte[] file ;

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    public byte[] getFile() {
        return file;
    }

    public void setFile(byte[] file) {
        this.file = file;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getAuth() {
        return auth;
    }

    public void setAuth(String auth) {
        this.auth = auth;
    }

    public String getFrom() {
        return from;
    }

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

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    public String getSubject() {
        return subject;
    }

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

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}

三、email简单工具类

package cn.pkulaw.fblx.util.email;

import org.apache.tomcat.util.security.MD5Encoder;
import sun.security.provider.MD5;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * @Author: WXM
 * @Description:
 * @Date: create in 2021/2/1 13:25
 */

public class EmailUtils  {

    //利用带用户名密码或授权码 授权的邮箱服务器 发送简单的email
    public static void sendSimWithAuth(MailEntity mail){
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", mail.getAddr());
        properties.put("mail.smtp.auth", "true");
        if(null!=mail.getPort()){
            properties.put("mail.smtp.port",mail.getPort());
        }
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mail.getFrom(),mail.getAuth());
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(mail.getFrom()));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(mail.getTo()));
            message.setSubject(mail.getSubject());
            message.setText(mail.getText());
            Transport.send(message);

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

    //利用带用户名密码或授权码 授权的邮箱服务器 发送带附件的email
    public static void sendLocalServerWithAuth(MailEntity mail){
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", mail.getAddr());
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true");

        if(null!=mail.getPort()){
            properties.put("mail.smtp.port",mail.getPort());
        }
        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mail.getFrom(), mail.getAuth());
            }
        };
        Session session = Session.getInstance(properties,auth);
        session.setDebug(true);

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(mail.getFrom()));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(mail.getTo()));
            message.setSubject(mail.getSubject());
            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();
            // 消息
            messageBodyPart.setText(mail.getText());
            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart);
            // 附件部分
            messageBodyPart = new MimeBodyPart();
            //设置附件文件名+文件类型
            String filename = mail.getFileName();
            messageBodyPart.setFileName(filename);
            //设置附加实体
            ByteArrayInputStream bais = new ByteArrayInputStream(mail.getFile());
            DataSource source = new ByteArrayDataSource(bais,mail.getFileType());
            messageBodyPart.setDataHandler(new DataHandler(source));
            multipart.addBodyPart(messageBodyPart);
            // 发送完整消息
            message.setContent(multipart);
            Transport.send(message);

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

}

四、测试类

    @Test
    public void test10(){
        //获取有标题列的excel对象
        String[] title = {"编号","Gid","标题","发文字号","发布部门","发布时间","数据状态","后台","库别","匹配类型"};
        XSSFWorkbook workBook = ExcelUtils.getExcelWithTitle(title);
        MailEntity me = new MailEntity();
        me.setFrom("xxx@qq.com");
        me.setTo("xxx@xxx.com");
        me.setAddr("smtp.qq.com");
        me.setAuth("xxx");
        me.setSubject("test1");
        me.setText("test1");
        me.setFileName("test1.xlsx");
        me.setFileType("application/excel");

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workBook.write(baos);
            byte[] bytes = baos.toByteArray();
            me.setFile(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        EmailUtils.sendQQServerWithAuth(me);
    }

    @Test
    public void test13(){
        //获取有标题列的excel对象
        String[] title = {"编号","Gid","标题","发文字号","发布部门","发布时间","数据状态","后台","库别","匹配类型"};
        XSSFWorkbook workBook = ExcelUtils.getExcelWithTitle(title);
        MailEntity me = new MailEntity();
        me.setFrom("xxx@xxx.com");
        me.setTo("xxx@xxx.com");
        me.setAddr("smtp.xxx.com");
        me.setAuth("xxx");
        me.setSubject("test1");
        me.setText("test1");
        me.setFileName("test1.xlsx");
        me.setFileType("application/excel");
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workBook.write(baos);
            byte[] bytes = baos.toByteArray();
            me.setFile(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        EmailUtils.sendLocalServerWithAuth(me);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值