Spring 多邮箱源发送邮件
时间: 2024-05-04 17:20:44 浏览: 8
在 Spring 中,我们可以使用 JavaMailSender 类发送邮件。要发送多个邮件,我们需要使用不同的邮箱源进行身份验证和发送。以下是一个示例代码,它使用 Gmail 和 Hotmail 邮箱源发送邮件:
```java
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
public class EmailService {
private JavaMailSender mailSender;
public EmailService() {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("smtp.gmail.com"); // Gmail 邮箱源
sender.setPort(587);
sender.setUsername("your-gmail-email-address@gmail.com");
sender.setPassword("your-gmail-password");
// 添加 Hotmail 邮箱源
Properties props = sender.getJavaMailProperties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.live.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.ssl.trust", "smtp.live.com");
props.put("mail.smtp.user", "your-hotmail-email-address@hotmail.com");
props.put("mail.smtp.password", "your-hotmail-password");
this.mailSender = sender;
}
public void sendEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
this.mailSender.send(message);
}
}
```
在上面的代码中,我们创建了一个 JavaMailSenderImpl 对象,它使用 Gmail 邮箱源进行身份验证和发送。然后,我们添加了 Hotmail 邮箱源的属性,以便使用多个邮箱源。最后,我们使用 SimpleMailMessage 类构建邮件,调用 JavaMailSender 的 send() 方法发送邮件。
在使用多个邮箱源发送邮件时,请确保您使用了正确的端口和其他属性。您可以在邮箱提供商的帮助文档中找到这些信息。