当前位置:   article > 正文

java实现邮件发送_java实现发送邮件

java实现发送邮件

概述

SMTP电子邮件传输的协议:
SMTP是一种提供可靠且有效的电子邮件传输的协议。SMTP是建立在FTP文件传输服务上的一种邮件服务,主要用于系统之间的邮件信息传递,并提供有关来信的通知。SMTP独立于特定的传输子系统,且只需要可靠有序的数据流信道支持,SMTP的重要特性之一是其能跨越网络传输邮件,即“SMTP邮件中继”。使用SMTP,可实现相同网络处理进程之间的邮件传输,也可通过中继器或网关实现某处理进程与其他网络之间的邮件传输。

手把手教java实现邮件发送

第一步:配置邮箱服务

1、以QQ邮箱举例,进入邮箱-设置-账号-POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,开启SMTP服务
请添加图片描述
2、开启SMTP服务后会获得授权码,复制为后期配置邮箱password。后期如若修改授权码可进入管理服务-安全设置-POP3/IMAP/SMTP/Exchange/CardDAV 服务(已开启)点击生成授权码
3、进入管理服务-账号设置-默认发信账号,复制默认发信账号为后期配置邮箱username
4、进入管理服务-安全设置-POP3/IMAP/SMTP/Exchange/CardDAV 服务(已开启)点击配置SMTP/IMAP方法,里面有详细配置方法请添加图片描述
到这里QQ邮箱配置完成。

第二步:集成邮件依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • 1
  • 2
  • 3
  • 4

第三步:配置文件集成邮箱配置参数

mail.send.from=你的QQ邮箱完整的地址
spring.mail.host=smtp.qq.com
spring.mail.username=默认发信账号
spring.mail.password=授权码
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.port=587
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

第四步:编写邮件发送客户端MessageClient

package com.iflytek.email.emailapiservice.commons.message;

import org.apache.commons.lang3.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

@Slf4j
@Component
public class MessageClient {

    public final static MessageSendResponse serverNotAvailable = new MessageSendResponse(false, "Oops, Email could not be delivered.");
    public final static MessageSendResponse sendSuccessful = new MessageSendResponse(true, "");

    /**
     *  邮件发送方
     */
    @Value("${mail.send.from}")
    public String mailSendFrom;

    @Autowired
    private JavaMailSender mailSender;

    public MessageSendResponse sendEmailMessageNoRequest(String title, String content, String receiver) {

        if (StringUtils.isBlank(receiver)) {
            throw new RuntimeException("email receivers can't be empty");
        }

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper;

        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailSendFrom);
            helper.setTo(receiver);// 接收者
            helper.setSubject(title);// 邮件主题
            helper.setText(content, true);// 邮件内容, 不是html也没关系
            long t1 = System.currentTimeMillis();
            mailSender.send(mimeMessage);// 发送邮件
            long t2 = System.currentTimeMillis();
            log.debug("email send to {} successful, take {} seconds", receiver, (t2 - t1) / 1000);
            return sendSuccessful;
        } catch (Exception e) {
            log.error("send email to {} direct got error {}", receiver, e);
            return serverNotAvailable;
        }
    }


    @AllArgsConstructor
    public static class MessageSendResponse {
        private Boolean success;
        private String reason;

        public Boolean isSuccessful() {
            return success;
        }

        public String getReason() {
            return reason;
        }
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72

第五步:编写controller

package com.iflytek.email.emailapiservice.controller;

import com.iflytek.email.emailapiservice.service.SendEmailDemoService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/email")
public class SendEmailController {

    @Resource
    private SendEmailDemoService sendEmailDemoService;

    @GetMapping("/test")
    public void sendEmail(){
        sendEmailDemoService.sendEmail();
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

第六步:编写service

package com.iflytek.email.emailapiservice.service;

import com.iflytek.email.emailapiservice.commons.message.MessageClient;

public interface SendEmailDemoService {

    MessageClient.MessageSendResponse sendEmail();
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

第七步:编写impl

package com.iflytek.email.emailapiservice.service.impl;

import com.iflytek.email.emailapiservice.commons.message.MessageClient;
import com.iflytek.email.emailapiservice.service.SendEmailDemoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class SendEmailDemoServiceImpl implements SendEmailDemoService {

    @Resource
    private MessageClient messageClient;

    @Override
    public MessageClient.MessageSendResponse sendEmail() {
        // 内容
        String content = "发送了一封邮件,此邮件是一封测试邮件,收到请忽略。";
        // 主题
        String title = "邮件主题";
        // 邮件接收者
        String email="XXXXXXXXX@XXX.com";
        MessageClient.MessageSendResponse messageSendResponse = messageClient.sendEmailMessageNoRequest(title, content, email);
        if (!messageSendResponse.isSuccessful()) {
            log.error("messageSendResponse fail");
        }
        return messageSendResponse;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

第八部:测试

请添加图片描述
到此邮件发送开发完毕。

注:参数,content内容可以根据实际情况修改

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/728300
推荐阅读
相关标签
  

闽ICP备14008679号