java发送邮件email实战

1.首先在项目中增加依赖,在pom文件中添加如下坐标

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

2.发邮件工具类如下

package com.example.demo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class MailSender {
    private static volatile JavaMailSenderImpl sender;
    private static ReentrantLock lock = new ReentrantLock();

    private static void initServer() {
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        // 我用的 163 邮箱
        senderImpl.setHost("smtp.163.com");
        senderImpl.setPort(25);
        senderImpl.setUsername("你的邮箱");
        senderImpl.setPassword("你的授权码");
        Properties prop = new Properties();
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.timeout", "25000");
        prop.put("mail.smtp.ssl.enable", "false");
        senderImpl.setJavaMailProperties(prop);
        senderImpl.setDefaultEncoding("UTF-8");
        sender = senderImpl;
    }

    public static void sendHTML(String from, String[] recipients,
                                String subject, String content) {
        try {
            sendAttachment(new InternetAddress(from), recipients, null, subject, null, null, content);
        } catch (MessagingException e) {
            log.error("发送邮件异常,e:{}", e);
        }

    }

    /**
     * 发邮件
     *
     * @param from       发件人
     * @param recipients 收件人
     * @param cc         未知
     * @param subject    邮件主题
     * @param fileName   文件名称
     * @param file       文件
     * @param text       邮件正文
     */
    public static void sendAttachment(InternetAddress from, String[] recipients, String[] cc,
                                      String subject, String fileName, File file, String text) {
        initServer();
        MimeMessage mimeMessage = sender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            helper.setFrom(from);
            helper.setTo(recipients);
            if (cc != null && cc.length > 0) {
                helper.setCc(cc);
            }
            helper.setSubject(subject);
            if (fileName != null && file != null) {
                helper.addAttachment(fileName, file);
            }
            helper.setSubject(subject);
            helper.setText("", text);
            sender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("发送邮件异常,e:{}", e);
        }
    }

    /**
     * 带附件发送邮件
     *
     * @param from              发件人
     * @param recipients        收件人
     * @param cc                未知
     * @param subject           邮件主题
     * @param fileName          附件文件名
     * @param inputStreamSource 附件文件
     * @param text              邮件正文
     */
    public static void sendAttachment2(InternetAddress from, String[] recipients, String[] cc,
                                       String subject, String fileName, InputStreamSource inputStreamSource, String text) {
        initServer();
        MimeMessage mimeMessage = sender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
            helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            helper.setFrom(from);
            helper.setTo(recipients);
            if (cc != null && cc.length > 0) {
                helper.setCc(cc);
            }
            helper.setSubject(subject);
            if (fileName != null) {
                helper.addAttachment(fileName, inputStreamSource);
            }
            helper.setText(text, true);
            sender.send(mimeMessage);
        } catch (Exception e) {
            log.error("发送邮件异常,e:{}", e);
        }
    }
}

3.发送邮件的服务端


import com.example.demo.utils.MailSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.MailSendException;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MailService {
    private String mailText = "xxx发来邮件";
    private String mailer = "接收邮箱";

    public boolean sendMail() {
        boolean accept = false;
        try {
            MailSender.sendHTML("发送邮箱", new String[]{mailer}, mailText, "巴拉拉小魔仙");

            accept = true;
        } catch (MailSendException mailSendException) {
            log.info("邮件发送失败", mailSendException);
            // 是否需要重试
        } catch (Exception e) {
            log.error("邮件发送失败,收件人:{}", mailer, e);
        }
        return accept;
    }
}

4.需要打开对应邮箱的smtp服务
并且获取到授权码
那网易邮箱举例子如下
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荼白z

感谢老板请我喝咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值