当前位置:网站首页>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
边栏推荐
- 【最详细】最新最全Redis面试大全(50道)
- FileInputStream and fileoutputstream
- 10 000 volumes - Guide de l'investisseur en valeur [l'éducation d'un investisseur en valeur]
- Margin left: -100% understanding in the Grail layout
- [set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)
- Industrial resilience
- Lombok -- simplify code
- LeetCode
- Topic | synchronous asynchronous
- Basic knowledge about SQL database
猜你喜欢

Summary of abnormal mechanism of interview

Leetcode 213: 打家劫舍 II

Store WordPress media content on 4everland to complete decentralized storage

Interview questions about producers and consumers (important)

3311. Longest arithmetic

PAT甲级真题1166

Arduino Serial系列函数 有关print read 的总结

Final, override, polymorphism, abstraction, interface

你开发数据API最快多长时间?我1分钟就足够了

Discussion on some problems of array
随机推荐
File operation serialization recursive copy
Download address collection of various versions of devaexpress
Topic | synchronous asynchronous
Distributed transactions
[set theory] order relation (partial order relation | partial order set | example of partial order set)
“百度杯”CTF比赛 2017 二月场,Web:爆破-1
论文学习——鄱阳湖星子站水位时间序列相似度研究
VMWare网络模式-桥接,Host-Only,NAT网络
Circuit, packet and message exchange
最全SQL与NoSQL优缺点对比
PAT甲级真题1166
Hash table, generic
7.2刷题两个
Advanced API (UDP connection & map set & collection set)
Advanced API (use of file class)
4279. Cartesian tree
LeetCode
Distributed ID
【最详细】最新最全Redis面试大全(50道)
How long is the fastest time you can develop data API? One minute is enough for me