基于spring-boot的邮件发送的代码

1.pom.xml引入如下jar
<dependency>
 <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.在application.properties里配置如下信息:
spring.mail.properties.mail.smtp.connecttimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000
spring.mail.host=xxxxxxx
spring.mail.username=xxxx
spring.mail.password=xxx
spring.mail.port=25

spring.mail.properties.mail.smtp.auth=true

//---------------------------------------------------------------

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 基于spring-boot的邮件发送功能测试
 * @author Dabria_ly
 * 2017年8月10日
 */
@Component("mailtest")
@Controller
@RequestMapping("/Mailtest")
public class TestEMailUtil {


@Autowired
    private JavaMailSender mailSender;//JavaMailSender邮件发送类

@ResponseBody
@RequestMapping("/toSendMail")
public String testSendMail(){
//邮件接收者,多个邮件用;分割
String mailReceivers = "xxxx.com;xxxx@163.com";
String subject = "邮件主题";//邮件主题
String body = "邮件内容";//邮件内容

if(EMailUtilsWay.sendMail(mailSender, mailReceivers, subject, body)){
return "邮件发送成功";
}else{
return "邮件发送失败";
}
}
}

//-------------------------------------------------------------------------------------------

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


/**
 * 发送邮件的工具类(基于spring-boot的邮件发送功能)
 * @author Dabria_ly
 * 2017年8月10日
 *
 */
@Component
public class EMailUtilsWay {


    private static final Logger LOG = LoggerFactory.getLogger(EMailUtilsWay.class);
    /**
     * 发送预警邮件
     * @param mailSender      : JavaMailSender邮件发送类
     * @param mailReceivers   : 邮件接收者
     * @param subject         : 邮件主题
     * @param body            : 邮件内容
     * @return
     */
    public static boolean sendMail(JavaMailSender mailSender,String mailReceivers,String subject,String body) {
        if (StringUtils.hasText(mailReceivers)) {
            String[] mails = mailReceivers.split(";");
            return sendMail(mailSender,mails, subject, body);
        }
        return false;
    }


    public static boolean sendMail(JavaMailSender mailSender,String[] mails,String subject,String body) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("nopo");//设置邮件发送者名称
            message.setTo(mails);
            message.setSubject(subject);
            message.setText(body);
            mailSender.send(message);
            return  true;
        } catch (Exception ex) {
            LOG.error(String.format("发送邮件失败,%s", mails), ex);
        }
        return  false;
    }
}

### 关于 `spring-boot-starter-mail` 的发送邮件工具类 `spring-boot-starter-mail` 是 Spring Boot 提供的一个 Starter,用于简化电子邮件发送功能。它基于 JavaMail API 并提供了自动配置支持[^3]。通过引入此依赖项并完成必要的配置,可以轻松实现邮件发送的功能。 #### 1. 添加依赖 为了使用 `spring-boot-starter-mail` 功能,在项目的构建文件中需添加如下依赖: 对于 Maven 构建工具: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 对于 Gradle 构建工具: ```gradle implementation 'org.springframework.boot:spring-boot-starter-mail' ``` #### 2. 配置邮箱服务 在 `application.properties` 或 `application.yml` 文件中配置邮件服务器的信息。以下是常见的配置选项: ##### application.properties 示例: ```properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=user@example.com spring.mail.password=yourpassword spring.mail.protocol=smtp spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` ##### application.yml 示例: ```yaml spring: mail: host: smtp.example.com port: 587 username: user@example.com password: yourpassword protocol: smtp properties: mail: smtp: auth: true starttls: enable: true ``` 以上配置指定了 SMTP 服务器地址、端口、用户名、密码以及其他连接属性。注意保护敏感信息的安全性[^4]。 #### 3. 创建邮件发送工具类 下面是一个简单的工具类示例,展示如何利用 `JavaMailSender` 接口发送邮件: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @Service public class EmailService { @Autowired private JavaMailSender emailSender; public void sendSimpleEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); emailSender.send(message); // 发送简单文本邮件 } public void sendHtmlEmail(String to, String subject, String htmlContent) throws MessagingException { MimeMessage mimeMessage = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setTo(to); helper.setSubject(subject); helper.setText(htmlContent, true); // 设置为HTML格式 emailSender.send(mimeMessage); // 发送HTML邮件 } public void sendAttachmentEmail(String to, String subject, String text, File attachmentFile) throws MessagingException { MimeMessage mimeMessage = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setTo(to); helper.setSubject(subject); helper.setText(text); FileSystemResource fileSystemResource = new FileSystemResource(attachmentFile); helper.addAttachment(fileSystemResource.getFilename(), fileSystemResource); emailSender.send(mimeMessage); // 带附件的邮件 } } ``` 上述代码展示了三种类型的邮件发送方式:纯文本邮件、HTML 格式邮件以及带附件的邮件。每种方法都封装在一个独立的方法中以便调用[^5]。 #### 4. 测试邮件发送功能 可以通过编写单元测试或控制器接口来验证邮件发送功能是否正常工作。例如: ```java @RestController @RequestMapping("/email") public class EmailController { @Autowired private EmailService emailService; @PostMapping("/send-simple-email") public ResponseEntity<String> sendSimpleEmail(@RequestParam String recipient, @RequestParam String subject, @RequestParam String content) { try { emailService.sendSimpleEmail(recipient, subject, content); return ResponseEntity.ok("Simple email sent successfully!"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } } } ``` #### 注意事项 - 确保使用的 SMTP 服务器允许外部访问,并已启用所需的权限(如 STARTTLS)。 - 如果涉及敏感数据(如密码),建议采用加密存储或其他安全措施以防止泄露[^6]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值