当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
An overview of IfM Engage
Summary of Arduino serial functions related to print read
[HCAI] learning summary OSI model
Beginners use Minio
Warehouse database fields_ Summary of SQL problems in kingbase8 migration of Jincang database
URL programming
【已解决】Unknown error 1146
【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
Some experiences of Arduino soft serial port communication
TypeScript let與var的區別
Summary of abnormal mechanism of interview
【CMake】CMake链接SQLite库
Operation and maintenance technical support personnel have hardware maintenance experience in Hong Kong
Advanced API (serialization & deserialization)
Split small interface
SecureCRT取消Session记录的密码
Docker builds MySQL: the specified path of version 5.7 cannot be mounted.
Common analysis with criteria method
7.2刷题两个
[set theory] order relation (partial order relation | partial order set | example of partial order set)









