柚子快报邀请码778899分享:java 邮件发送的几种方式
1、使用JavaMail发送邮件
1.1 添加依赖
1.2 简单邮件发送
@Test()
public void testSend() throws Exception {
// 连接邮件服务器的参数配置
Properties props = new Properties();
// 设置用户的认证方式
props.setProperty("mail.smtp.auth", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// 创建定义整个应用程序所需的环境信息的 Session 对象
Session session = Session.getInstance(props,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(name, pwd);
}
});
// 创建消息对象
MimeMessage message = new MimeMessage(session);
// 邮件消息头
message.setFrom(new InternetAddress(name)); // 发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 收件人
message.setSubject("邮件测试1");
message.setText("Hello, java mail!");
// 发送邮件
Transport.send(message);
}
2、使用Spring的JavaMailSenderImpl发送邮件
2.1 添加依赖
2.2 简单邮件发送
@Test
public void testSend2() throws MessagingException {
JavaMailSenderImpl sendService = new JavaMailSenderImpl();
sendService.setHost(host);
sendService.setPort(port);
sendService.setUsername(name);
sendService.setPassword(pwd);
MimeMessage msg = sendService.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
helper.setTo(to);
helper.setFrom(name);
helper.setSubject("邮件测试2");
helper.setText("Hello, spring!", true);
sendService.send(msg);
}
3、使用Apache commons-email发送邮件
3.1 添加依赖
3.2 简单邮件发送
@Test
public void testSend3() throws EmailException {
Email email = new SimpleEmail();
email.setHostName(host);
email.setSmtpPort(port);
email.setAuthenticator(new DefaultAuthenticator(name, pwd));
email.setCharset("UTF-8");
email.setFrom(name);
email.addTo(to);
email.setSubject("测试邮件3");
email.setMsg("Hello, commons-email!");
email.send();
}
柚子快报邀请码778899分享:java 邮件发送的几种方式
相关文章
发表评论