扫码一下
查看教程更方便
通过使用 spring boot restful web 服务,我们可以使用 gmail 传输层安全性发送电子邮件。 在本章中,让我们详细了解如何使用此功能。
首先,我们需要在构建配置文件中添加 spring boot starter mail 依赖项。
maven 用户可以将以下依赖项添加到 pom.xml 文件中。
org.springframework.boot
spring-boot-starter-mail
gradle 用户可以在 build.gradle 文件中添加以下依赖项。
compile('org.springframework.boot:spring-boot-starter-mail')
主要 spring boot 应用程序类文件的代码如下
package com.jiyik.emailapp;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
/**
* @author jiyik.com
*/
@springbootapplication
public class emailappapplication {
public static void main(string[] args) {
springapplication.run(emailappapplication.class, args);
}
}
我们可以编写一个简单的 rest api 以发送到 rest controller 类文件中的电子邮件,如下所示。
package com.jiyik.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
public class emailcontroller {
@requestmapping(value = "/sendemail")
public string sendemail() {
return "email sent successfully";
}
}
我们可以编写一个方法来发送带有附件的电子邮件。 定义 mail.smtp
属性并使用 passwordauthentication
。
private void sendmail() throws addressexception, messagingexception, ioexception {
properties props = new properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
session session = session.getinstance(props, new javax.mail.authenticator() {
protected passwordauthentication getpasswordauthentication() {
return new passwordauthentication("tutorialspoint@gmail.com", "");
}
});
message msg = new mimemessage(session);
msg.setfrom(new internetaddress("tutorialspoint@gmail.com", false));
msg.setrecipients(message.recipienttype.to, internetaddress.parse("tutorialspoint@gmail.com"));
msg.setsubject("tutorials point email");
msg.setcontent("tutorials point email", "text/html");
msg.setsentdate(new date());
mimebodypart messagebodypart = new mimebodypart();
messagebodypart.setcontent("tutorials point email", "text/html");
multipart multipart = new mimemultipart();
multipart.addbodypart(messagebodypart);
mimebodypart attachpart = new mimebodypart();
attachpart.attachfile("/var/tmp/image19.png");
multipart.addbodypart(attachpart);
msg.setcontent(multipart);
transport.send(msg);
}
现在,从 rest api 调用上面的 sendmail()
方法,如图所示
@requestmapping(value = "/sendemail")
public string sendemail() throws addressexception, messagingexception, ioexception {
sendmail();
return "email sent successfully";
}
注意
- 请在发送电子邮件之前在 gmail 帐户设置中打开允许不太安全的应用程序。