栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java中邮箱的相关使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中邮箱的相关使用

Java中邮箱的相关使用
  • 1 Java中邮箱的简介
  • 2 邮箱的使用
    • 1 Java原生操作邮箱
        • 1 导入maven坐标
        • 2 添加邮件工具类
    • 2 SpringBoot中操作邮箱
        • 0 准备一个好的SpringBoot环境
        • 1 添加maven坐标
        • 2 添加发送邮箱接口
        • 3 添加发送邮箱实现类
        • 4 添加配置文件
        • 5 添加一个控制器
        • 6 测试
  • 3 错误问题
        • 1 smtp.SMTPSendFailedException: 553 Mail from must equal authorized user

项目中常常有一些场景需要发送邮箱, 整理一下使用邮箱的相关实现

1 Java中邮箱的简介

电子邮件在网络中传输和网页一样需要遵从特定的协议,常用的电子邮件协议包括 SMTP,POP3,IMAP。其中邮件的创建和发送只需要用到 SMTP协议( Simple Mail Transfer Protocol) ,即简单邮件传输协议。

2 邮箱的使用 1 Java原生操作邮箱 1 导入maven坐标
    
      com.sun.mail
      javax.mail
      1.5.6
    
2 添加邮件工具类
public class MailTest {

    // 发邮件账号
    public static String sendEmailAccount = "Xxx@163.com";
    // 发邮箱账号授权码
    public static String sendEmailPassword = "****";
    // 发邮箱账号主机
    public static String sendEmailSMTPHost = "smtp.163.com";
    // 发邮箱协议
    public static String sendEmailProtocol = "smtp";
    // 邮件的标题
    public static String sendEmailSubject = "邮件的标题";
    // 邮件的内容
    public static String sendEmailContext = "邮件的内容";
    // 收邮箱账号
    public static String receiveMailAccount = "Xxx@qq.com";

    public static void main(String[] args) {
        // 配置参数
        Properties prop = new Properties();
        // 发件人的邮箱的SMTP 服务器地址(不同的邮箱,服务器地址不同,如139和qq的邮箱服务器地址不同)
        prop.setProperty("mail.host", sendEmailSMTPHost);
        // 使用的协议(JavaMail规范要求)
        prop.setProperty("mail.transport.protocol", sendEmailProtocol);
        // 需要请求认证
        prop.setProperty("mail.smtp.auth", "true");

        // 使用JavaMail发送邮件的5个步骤
        // 1 创建session
        Session session = Session.getInstance(prop);
        // 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        Transport ts = null;
        try {
            // 2 通过session得到transport对象
            ts = session.getTransport();
            // 3 使用账户和授权码
            ts.connect(sendEmailSMTPHost, sendEmailAccount, sendEmailPassword);
            // 4 创建邮件
            Message message = createSimpleMail(session);
            // 5 发送邮件
            ts.sendMessage(message, message.getAllRecipients());
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭transport对象
                ts.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    
    public static MimeMessage createSimpleMail(Session session)
            throws MessagingException {
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明发件人
        message.setFrom(new InternetAddress(sendEmailAccount));
        // 指明收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveMailAccount));
        // 可选 添加收件人
//        message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiveMailAccount));
        //    Cc: 抄送(可选)
//        message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(receiveMailAccount));
        //    Bcc: 密送(可选)
//        message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(receiveMailAccount));

        // 邮件的标题
        message.setSubject(sendEmailSubject,"UTF-8");
        // 邮件的文本内容
        message.setContent(sendEmailContext, "text/html;charset=UTF-8");

        // 设置显示发件时间
        message.setSentDate(new Date());

        return message;
    }
2 SpringBoot中操作邮箱 0 准备一个好的SpringBoot环境 1 添加maven坐标
    
      org.springframework.boot
      spring-boot-starter-mail
    
2 添加发送邮箱接口
public interface MailService {


    
    public void sendMail(String to, String subject, String content, ByteArrayOutputStream os,
            String attachmentFilename) throws Exception;

}
3 添加发送邮箱实现类
@Component
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.fromMail.addr}")
    private String from;

    
    @Override
    public void sendMail(String to, String subject, String content, ByteArrayOutputStream os,
            String attachmentFilename) throws Exception {

        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content);

            // 判断附件是否存在
            if (null != os){
                InputStreamSource inputStreamSource = new ByteArrayResource(os.toByteArray());
                mimeMessageHelper.addAttachment(attachmentFilename, inputStreamSource);
            }
            mailSender.send(mimeMessage);
            log.info("邮件发送完成");
        } catch (Exception e) {
            log.error("邮件发送失败 , ={}",e);

        }

    }
}
4 添加配置文件
# 邮箱服务器地址
spring.mail.host=smtp.163.com
# 用户名
spring.mail.username=Xxx@163.com
# 密码
spring.mail.password=******
spring.mail.default-encoding=UTF-8
#spring.mail.port=587 # 使用报错
spring.mail.port=25   # 使用ok
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
# 来发送邮件账号
mail.fromMail.addr=Xxx@163.com

5 添加一个控制器
@Controller
@RequestMapping("/hello")
public class HelloWorld {
    public static String sendEmailSubject = "邮件的标题";
    public static String sendEmailContext = "邮件的内容";
    public static String receiveMailAccount = "Xxx@qq.com";

    @Autowired
    private MailService mailService;

    @GetMapping("/sendMail")
    @ResponseBody
    public String sendMail() throws Exception {
        //  邮件接受者   邮件标题    邮件内容    附件   附件名称
      mailService.sendMail(receiveMailAccount,sendEmailSubject,sendEmailContext,null,"");

        return "Hello Wrold";
    }
   
}  
6 测试

在地址栏访问:

http://localhost:8080/hello/sendMail

控制台日志:

// 2021-11-01 18:04:41.535  INFO 16576 --- [nio-8080-exec-1] c.cf.demo.service.impl.MailServiceImpl   : 邮件发送完成

查看邮箱,邮件已送达.

3 错误问题 1 smtp.SMTPSendFailedException: 553 Mail from must equal authorized user

发邮件的人的账号填写错误, 要和授权码的账户一致.

// 接收邮件服务器:imap.qq.com,使用SSL,端口号993。

// 发送邮件服务器:smtp.qq.com,使用SSL,端口号465或587。 使用25时成功

参考资料:

https://www.cnblogs.com/new-life/p/10549837.html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/389641.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号