JavaMail发送邮件Demo

JavaMail发送邮件Demo

Maven依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!-- lombok 用于简化JavaBean结构 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

JavaMail工具类

public class JavaMailUtil {

    /*发件人邮箱*/
    public static String MYEMAILACCOUNT = "自己的邮箱";
    /*密码*/
    public static String MYEMAILPASSWORD = "uvgjctgmnfhziehe";
    /*SMTP服务器地址*/
    public static String MYEMAILSMTPHOST = "smtp.qq.com";
    /*收件人邮箱(测试)*/
    public static String RECEIVEMAILACCOUNT = "写自己的邮箱";

    /*1.创建参数配置,用于连接邮件服务器参数配置*/
    public static Properties properties = new Properties();

    /*2.创建会话*/
    public static Session session;

    /*3.创建邮件传输对象*/
    public static Transport transport;

    /**
     * 配置设置
     * @throws NoSuchProviderException
     * @throws MessagingException
     */
    public static void setProperties() throws NoSuchProviderException, MessagingException {
        /*使用的协议*/
        properties.setProperty("mail.transport.protocol","smtp");
        /*发件人邮箱SMTP服务器地址*/
        properties.setProperty("mail.smtp.host",MYEMAILSMTPHOST);
        /*需要的请求认证*/
        properties.setProperty("mail.smtp.auth","true");
        session = Session.getInstance(properties);
        session.setDebug(true);
        transport = session.getTransport();
        transport.connect(MYEMAILACCOUNT,MYEMAILPASSWORD);
    }

    /**
     * 创建邮件
     * @param mailBean
     * @return 邮件对象
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static MimeMessage getMimeMessage(MailBean mailBean) throws UnsupportedEncodingException,MessagingException{
        //1.创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //2.设置发送人
        mimeMessage.setFrom(new InternetAddress(MYEMAILACCOUNT,"迷人的猪肉佬","utf-8"));
        //3.设置收件人
        mimeMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(mailBean.getReceiveMail(),mailBean.getReceiverName(),"utf-8"));
        //4.设置邮件主题
        mimeMessage.setSubject(mailBean.getSuject(),"utf-8");

        return mimeMessage;
    }
    /**
     * 发送简单邮件
     * @param mailBean
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static void sendSimpleMail(MailBean mailBean) throws MessagingException, UnsupportedEncodingException {
        //1.创建邮件对象
        MimeMessage mimeMessage = getMimeMessage(mailBean);
        //2.设置文本信息
        mimeMessage.setText(mailBean.getText());
        //3.发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        transport.close();
    }


    /**
     * 发送Html邮件
     * @param mailBean
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static void sendHtmlMail(MailBean mailBean) throws UnsupportedEncodingException,MessagingException{
        //1.创建邮件对象
        MimeMessage mimeMessage = getMimeMessage(mailBean);
        //2.设置邮件文本信息
        mimeMessage.setText(mailBean.getText(),"utf-8","html");
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        transport.close();
    }

    /**
     * 发送有附件的邮件
     * @param mailBean
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static void sendAttchmentMail(MailBean mailBean,String url) throws UnsupportedEncodingException,MessagingException{
        //1.创建邮件对象
        MimeMessage mimeMessage = getMimeMessage(mailBean);
        /*创建附件节点*/
        MimeBodyPart attachment = new MimeBodyPart();
        DataHandler handler = new DataHandler(new FileDataSource(url));
        attachment.setDataHandler(handler);
        attachment.setFileName(MimeUtility.encodeText(handler.getName()));

        /*设置文件*/
        MimeMultipart multipart = new MimeMultipart();
        multipart.addBodyPart(attachment);

        /*设置整个邮件关系*/
        mimeMessage.setContent(multipart);
        /*设置发送时间*/
        mimeMessage.setSentDate(new Date());
        /*保存上面所有设置*/
        mimeMessage.saveChanges();

        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        transport.close();

    }

    /**
     * 发送附件+图片邮件
     * @param mailBean
     * @param imagePath 图片路径
     * @param filePath 文件路径
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static void sendAttchmentImageMail(MailBean mailBean,String imagePath,String filePath) throws MessagingException,UnsupportedEncodingException{
        //1.创建邮件对象
        MimeMessage mimeMessage = getMimeMessage(mailBean);
        mimeMessage.setText(mailBean.getText());

        /*邮件内容创建*/
        MimeBodyPart image = new MimeBodyPart();
        /*读取本地文件*/
        // 创建图片节点
        DataHandler dataHandler = new DataHandler(new FileDataSource(imagePath));
        /*将图片数据添加到节点*/
        image.setDataHandler(dataHandler);
        /*为该节点设置唯一ID*/
        image.setContentID("image_test");

        //创建文本节点
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这是一个图片<br/><img src='cid:image_test'/>","text/html;charset=UTF-8");

        MimeMultipart text_image = new MimeMultipart();
        text_image.addBodyPart(text);
        text_image.addBodyPart(image);
        text_image.setSubType("related");//关联关系
        MimeBodyPart textImage = new MimeBodyPart();
        textImage.setContent(text_image);
        /*创建附件节点*/
        MimeBodyPart attachment = new MimeBodyPart();
        DataHandler handler = new DataHandler(new FileDataSource(filePath));
        attachment.setDataHandler(handler);
        attachment.setFileName(MimeUtility.encodeText(handler.getName()));

        /*设置文件+图片+附件关系*/
        MimeMultipart multipart = new MimeMultipart();
        multipart.addBodyPart(textImage);
        multipart.addBodyPart(attachment);
        multipart.setSubType("mixed");

        /*设置整个邮件关系*/
        mimeMessage.setContent(multipart);
        /*设置发送时间*/
        mimeMessage.setSentDate(new Date());
        /*保存上面所有设置*/
        mimeMessage.saveChanges();

        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        transport.close();
    }

}

封装好的MailBean

@Data
public class MailBean {
    /*邮件主题*/
    private String suject;
    /*邮件正文*/
    private String text;
    /*附件*/
    private FileSystemResource file;
    /*附件名称*/
    private String attachmentname;
    /*内容ID,用于发送静态资源邮件使用*/
    private String contentId;
    /*收件人邮箱*/
    private String receiveMail;
    /*收件人名称*/
    private String receiverName;

    public static MailBean getMaileBean(){
        return new MailBean();
    }
}

测试类

public class JavaMailApp {
    public static void main(String[] args) throws NoSuchProviderException, MessagingException, UnsupportedEncodingException {

        JavaMailUtil.setProperties();

        MailBean mailBean = new MailBean();
        mailBean.setReceiveMail("收件人邮箱");
        mailBean.setReceiverName("唏嘘的猪肉佬");
        mailBean.setText("测试文本");
        mailBean.setSuject("测试邮件");

        System.out.println("-----发送简单邮件开始-----");
        JavaMailUtil.sendSimpleMail(mailBean);
        System.out.println("-----发送简单邮件结束-----");

        System.out.println("-----发送Html邮件开始-----");
        JavaMailUtil.sendHtmlMail(mailBean);
        System.out.println("-----发送Html邮件结束-----");

        System.out.println("-----发送附件邮件开始-----");
        JavaMailUtil.sendAttchmentMail(mailBean,"E:\\私人保存\\huan\\DSC_0099.jpg");
        System.out.println("-----发送附件邮件结束");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值