当前位置:网站首页>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
边栏推荐
- File operation serialization recursive copy
- C WinForm framework
- Chrome 98 Private Network Access problem w/ disabled web security: Request had no target IP address
- 【最详细】最新最全Redis面试大全(50道)
- Strategy mode
- Arduino Serial系列函数 有关print read 的总结
- Why is data service the direction of the next generation data center?
- "Moss ma not found" solution
- SecureCRT password to cancel session recording
- 最全SQL与NoSQL优缺点对比
猜你喜欢
随机推荐
Jeecg menu path display problem
Jeecg data button permission settings
sharepoint 2007 versions
Talk about floating
[set theory] order relation (partial order relation | partial order set | example of partial order set)
Book recommendation~
Strategy mode
Deep learning parameter initialization (I) Xavier initialization with code
Final, override, polymorphism, abstraction, interface
【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
Basic components and intermediate components
TreeMap
Thoughts on project development
Comparison of advantages and disadvantages between most complete SQL and NoSQL
Advanced API (multithreading)
Beginners use Minio
GStreamer ffmpeg avdec decoded data flow analysis
【已解决】SQLException: Invalid value for getInt() - ‘田鹏‘
[most detailed] latest and complete redis interview book (50)
IO stream system and FileReader, filewriter