当前位置:网站首页>Mail sending of vertx
Mail sending of vertx
2022-07-03 07:25:00 【Sleeping Empire】
Introduce
Vert.x Email client , Used through the local mail server (eg. postfix) Or external mail server (eg. googlemail or aol) send out SMTP E-mail .
1. maven Project dependence
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-config-yaml</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-mail-client</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.lance.common</groupId>
<artifactId>vertx-common-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
2.YAML File configuration
server:
port: 18000
mail:
hostname: smtp.mxhichina.com
username: [email protected]
password: [email protected]
port: 25
3. Start loading profile , And into the config In the middle
public class MailApplication {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
ConfigRetriever retriever = readYaml(vertx);
retriever.getConfig(json -> {
JsonObject object = json.result();
MailHelper dbHelper = new MailHelper(object.getJsonObject("mail"), vertx);
dbHelper.afterPropertiesSet();
DeploymentOptions options = new DeploymentOptions().setConfig(object);
vertx.deployVerticle(MainApp.class.getName(), options);
});
}
private static ConfigRetriever readYaml(Vertx vertx) {
ConfigStoreOptions store = new ConfigStoreOptions()
.setType("file")
.setFormat("yaml")
.setOptional(true)
.setConfig(new JsonObject().put("path", "application.yaml"));
return ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(store));
}
}
4.Mail client Connection configuration
public class MailHelper {
private final JsonObject object;
private final Vertx vertx;
@Getter
private static MailClient mailClient;
@Getter
private static String from;
/**
* initialization mail client Connect
*/
public void afterPropertiesSet() {
ConfigProperties.MailProperties properties = object.mapTo(ConfigProperties.MailProperties.class);
from = properties.getUsername();
MailConfig config = new MailConfig();
config.setHostname(properties.getHostname());
config.setUsername(from);
config.setPassword(properties.getPassword());
config.setPort(properties.getPort());
config.setStarttls(properties.getStarttls());
mailClient = MailClient.create(vertx, config);
}
}
5.Email Send execution instance
public class UserService {
private final static String SUFFIX_JAR = ".jar!";
/**
* send text content
*/
public void sendMessage(RoutingContext ctx) {
UserVo userVo = ctx.getBodyAsJson().mapTo(UserVo.class);
userVo.setHtml(false);
send(ctx, userVo, null);
}
/**
* send html content
*/
public void sendHtmlMessage(RoutingContext ctx) {
UserVo userVo = ctx.getBodyAsJson().mapTo(UserVo.class);
String html = "This is html text <a href=\"https://github.com/leelance/vertx-howto\" target=\"_blank\">Vertx--How To</a>";
userVo.setContent(html);
userVo.setHtml(true);
send(ctx, userVo, null);
}
/**
* send attach content
*/
public void sendAttachMessage(RoutingContext ctx) {
UserVo userVo = ctx.getBodyAsJson().mapTo(UserVo.class);
String html = "<h1>Hello world.</h1><p>This is attach text <a href=\"https://github.com/leelance/vertx-howto\" target=\"_blank\">Vertx--How To</a></p>";
userVo.setContent(html);
userVo.setHtml(true);
FileSystem fs = Vertx.vertx().fileSystem();
String path = getPathString("attach/file.txt");
Buffer buffer = fs.readFileBlocking(path);
MailAttachment attachment = MailAttachment.create();
attachment.setContentType("text/plain");
attachment.setData(buffer);
attachment.setName(new File(path).getName());
attachment.setDescription("Attachments can be created by the MailAttachment object using data stored in a Buffer, this supports base64 attachments.");
send(ctx, userVo, Collections.singletonList(attachment));
}
private void send(RoutingContext ctx, UserVo userVo, List<MailAttachment> attachments) {
MailMessage message = new MailMessage();
message.setFrom(MailHelper.getFrom());
message.setTo(userVo.getTo());
message.setCc(userVo.getCc());
message.setSubject(userVo.getSubject());
if (userVo.isHtml()) {
message.setHtml(userVo.getContent());
} else {
message.setText(userVo.getContent());
}
if (attachments != null) {
message.setAttachment(attachments);
}
MailHelper.getMailClient().sendMail(message)
.onSuccess(r -> {
log.info("===>send content mail success: {}", r);
ctx.json(R.data(r.toJson()));
})
.onFailure(e -> {
log.error("===> send content mail fail: ", e);
ctx.json(R.data(e.getMessage()));
});
}
/**
* Get the root directory if jar Run to get the relative path , On the contrary, it returns the root directory of the current thread
*
* @param fileName filename
* @return path
*/
private String getPathString(String fileName) {
if (StringUtils.isBlank(fileName)) {
throw new RuntimeException("filename is null");
}
URL path = Thread.currentThread().getContextClassLoader().getResource(fileName);
if (path != null && path.getPath().contains(SUFFIX_JAR)) {
return fileName;
} else {
return path == null ? "" : path.getPath();
}
}
}
6. Full address of the project
Send a screenshot of the email attachment
边栏推荐
- Homology policy / cross domain and cross domain solutions /web security attacks CSRF and XSS
- Talk about floating
- Dora (discover offer request recognition) process of obtaining IP address
- Pat grade a real problem 1166
- C WinForm framework
- Win 2008 R2 crashed at the final installation stage
- 专题 | 同步 异步
- [solved] unknown error 1146
- Some experiences of Arduino soft serial port communication
- C code production YUV420 planar format file
猜你喜欢
JS monitors empty objects and empty references
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
Common architectures of IO streams
“百度杯”CTF比赛 2017 二月场,Web:爆破-1
Final, override, polymorphism, abstraction, interface
7.2 brush two questions
File operation serialization recursive copy
3311. 最长算术
Spa single page application
在 4EVERLAND 上存储 WordPress 媒体内容,完成去中心化存储
随机推荐
[cmake] cmake link SQLite Library
Book recommendation~
691. 立方体IV
GStreamer ffmpeg avdec decoded data flow analysis
Win 2008 R2 crashed at the final installation stage
Introduction of transformation flow
2. E-commerce tool cefsharp autojs MySQL Alibaba cloud react C RPA automated script, open source log
Le Seigneur des anneaux: l'anneau du pouvoir
专题 | 同步 异步
When MySQL inserts Chinese into the database, there is a diamond question mark garbled code
Realize the reuse of components with different routing parameters and monitor the changes of routing parameters
TCP cumulative acknowledgement and window value update
Store WordPress media content on 4everland to complete decentralized storage
Lombok -- simplify code
IO stream system and FileReader, filewriter
Advanced APL (realize group chat room)
SQL create temporary table
JUC forkjoinpool branch merge framework - work theft
Jeecg request URL signature
Basic components and intermediate components