java 发送邮件使用模版
- User
java 发送邮件使用模版
- Assistant
在Java中发送带有模板的邮件是一种常见的做法,特别是在需要发送格式化邮件时(如欢迎邮件、密码重置邮件等)。模板邮件允许你预先设计好邮件的样式和内容,然后使用程序将特定数据填充进去。
下面是一个基本的例子,展示了如何使用Java发送带有模板的邮件。
第一步:添加依赖
你需要使用JavaMail API来发送邮件。你可以在项目的
pom.xml文件中添加以下依赖:<dependency> <groupId>com.sun.mail</groupId> <artifactId>jakarta.mail</artifactId> <version>2.0.1</version> </dependency>第二步:准备邮件模板
你可以使用类似于Freemarker或Thymeleaf的模板引擎来处理邮件模板。下面的例子使用Freemarker模板引擎。
创建模板文件
welcome_template.ftl<!DOCTYPE html> <html> <head> <title>Welcome</title> </head> <body> <h1>Welcome, ${userName}!</h1> <p>Thank you for joining our service. We are excited to have you on board!</p> </body> </html>第三步:编写Java代码
配置Freemarker
首先,配置Freemarker模板引擎:
import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; public class EmailTemplateLoader { private Configuration cfg; public EmailTemplateLoader() { cfg = new Configuration(Configuration.VERSION_2_3_29); cfg.setClassForTemplateLoading(this.getClass(), "/templates"); cfg.setDefaultEncoding("UTF-8"); } public String getProcessedTemplate(Map<String, Object> dataModel, String templateName) throws IOException, TemplateException { Template template = cfg.getTemplate(templateName); StringWriter stringWriter = new StringWriter(); template.process(dataModel, stringWriter); return stringWriter.toString(); } }发送邮件
接下来,编写发送邮件的代码:
import jakarta.mail.*; import jakarta.mail.internet.InternetAddress; import jakarta.mail.internet.MimeMessage; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class EmailSender { private static final String SMTP_HOST_NAME = "smtp.example.com"; private static final String SMTP_PORT = "587"; private static final String SMTP_USERNAME = "your-email@example.com"; private static final String SMTP_PASSWORD = "your-password"; public static void main(String[] args) { // 模拟数据 String userName = "John Doe"; // 准备邮件数据模型 Map<String, Object> dataModel = new HashMap<>(); dataModel.put("userName", userName); // 加载并处理模板 EmailTemplateLoader templateLoader = new EmailTemplateLoader(); String emailContent = ""; try { emailContent = templateLoader.getProcessedTemplate(dataModel, "welcome_template.ftl"); } catch (IOException | TemplateException e) { e.printStackTrace(); } // 发送邮件 Properties properties = new Properties(); properties.put("mail.transport.protocol", "smtp"); properties.put("mail.smtp.host", SMTP_HOST_NAME); properties.put("mail.smtp.port", SMTP_PORT); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(SMTP_USERNAME, SMTP_PASSWORD); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(SMTP_USERNAME)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com")); message.setSubject("Welcome to Our Service"); message.setContent(emailContent, "text/html"); Transport.send(message); System.out.println("Email sent successfully"); } catch (MessagingException e) { e.printStackTrace(); } } }注意事项
- 配置正确的SMTP信息:请确保你输入了正确的SMTP主机名、端口、用户名、密码等信息。
- 模板引擎:根据需要选择适合的模板引擎,这里选择了Freemarker,你也可以使用Thymeleaf等其他模板引擎。
- 错误处理:实际生产环境中对错误处理需要更加细致,这里只是简单输出错误信息。
通过上述代码,你可以在Java应用程序中使用模板引擎生成邮件内容并发送邮件。
- User
带图片的那种模版
- Assistant
在发送带有图片的邮件时,你需要注意的一个重要方面是如何将图片嵌入到邮件中。邮件中的图片可以是外部链接(线上图片)或内嵌的图片(嵌入到邮件内容本身)。为了示范方便,我们将展示如何发送包含内嵌图片的邮件。
我们仍然使用JavaMail API和Freemarker模板引擎来创建和发送邮件。首先,我们需要更新我们的模板文件以包含图片,然后修改我们的Java代码以处理内嵌图片。
第一步:创建模板文件
email_template_with_image.ftl<!DOCTYPE html> <html> <head> <title>Welcome</title> </head> <body> <h1>Welcome, ${userName}!</h1> <p>Thank you for joining our service. We are excited to have you on board!</p> <img src="cid:welcomeImage" alt="Welcome Image"/> </body> </html>第二步:准备邮件和图片资源
你需要准备你要嵌入的图片,并确保其路径正确。为了示范,我们假设图片文件位于
resources目录中,文件名为welcome_image.png。第三步:编写Java代码
配置Freemarker和准备模板引擎
与之前展示的一样,你可以使用以下代码来加载并处理Freemarker模板:
import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; public class EmailTemplateLoader { private Configuration cfg; public EmailTemplateLoader() { cfg = new Configuration(Configuration.VERSION_2_3_29); cfg.setClassForTemplateLoading(this.getClass(), "/templates"); cfg.setDefaultEncoding("UTF-8"); } public String getProcessedTemplate(Map<String, Object> dataModel, String templateName) throws IOException, TemplateException { Template template = cfg.getTemplate(templateName); StringWriter stringWriter = new StringWriter(); template.process(dataModel, stringWriter); return stringWriter.toString(); } }发送带有图片的邮件
接下来,编写Java代码来发送包含内嵌图片的邮件:
import jakarta.mail.*; import jakarta.mail.internet.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class EmailSender { private static final String SMTP_HOST_NAME = "smtp.example.com"; private static final String SMTP_PORT = "587"; private static final String SMTP_USERNAME = "your-email@example.com"; private static final String SMTP_PASSWORD = "your-password"; public static void main(String[] args) { // 模拟数据 String userName = "John Doe"; // 准备邮件数据模型 Map<String, Object> dataModel = new HashMap<>(); dataModel.put("userName", userName); // 加载并处理模板 EmailTemplateLoader templateLoader = new EmailTemplateLoader(); String emailContent = ""; try { emailContent = templateLoader.getProcessedTemplate(dataModel, "email_template_with_image.ftl"); } catch (IOException | TemplateException e) { e.printStackTrace(); } // 发送邮件 Properties properties = new Properties(); properties.put("mail.transport.protocol", "smtp"); properties.put("mail.smtp.host", SMTP_HOST_NAME); properties.put("mail.smtp.port", SMTP_PORT); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(SMTP_USERNAME, SMTP_PASSWORD); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(SMTP_USERNAME)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com")); message.setSubject("Welcome to Our Service"); // 创建多重消息部件 MimeMultipart multipart = new MimeMultipart("related"); // 第一部分 - HTML内容 BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailContent, "text/html"); multipart.addBodyPart(messageBodyPart); // 第二部分 - 图片内容 messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource("resources/welcome_image.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<welcomeImage>"); multipart.addBodyPart(messageBodyPart); // 设置邮件内容 message.setContent(multipart); Transport.send(message); System.out.println("Email sent successfully"); } catch (MessagingException | IOException e) { e.printStackTrace(); } } }注意事项
- 图片路径:确保图片路径正确。上例中图片路径设为
resources/welcome_image.png,实际情况中请根据需要调整路径。 - 处理异常:实际生产环境中对异常处理需要更加细致,这里只是简单输出错误信息。
- SMTP配置:确保SMTP配置正确。
通过上述代码,你可以在Java应用程序中使用模板引擎生成包含内嵌图片的邮件内容并发送邮件。
- 图片路径:确保图片路径正确。上例中图片路径设为
- User
The display: block property on the parent element prevents flex from having an effect. Try setting the display: block property on the parent to display: flex.
- Assistant
在使用CSS Flexbox布局模型时,重要的前提是你需要将父元素的
display属性设置为flex或inline-flex。如果设置了display: block,那么Flexbox布局将不会生效。而各子元素的布局也将不会按照Flexbox模型进行排列。以下是一个简单的例子,展示了如何正确使用Flexbox布局。
比较示例
不正确的用法(Flexbox无效)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flexbox Example</title> <style> .parent { display: block; /* 不正确:Flexbox布局不会生效 */ } .child { flex: 1; padding: 10px; border: 1px solid black; } </style> </head> <body> <div class="parent"> <div class="child">Child 1</div> <div class="child">Child 2</div> <div class="child">Child 3</div> </div> </body> </html>在这个例子中,即使你为
.child元素设置了flex: 1,但由于父元素.parent的display属性被设置为block,Flexbox布局无法生效。这些子元素将按照标准的块级元素行为排列,即从上到下排列。正确的用法(Flexbox生效)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flexbox Example</title> <style> .parent { display: flex; /* 正确:使用Flexbox */ } .child { flex: 1; padding: 10px; border: 1px solid black; } </style> </head> <body> <div class="parent"> <div class="child">Child 1</div> <div class="child">Child 2</div> <div class="child">Child 3</div> </div> </body> </html>在这个例子中,我们将
.parent的display属性设置为flex,子元素.child将会按照Flexbox布局模型进行排列。在此例中,每个子元素将会平分父容器的水平空间,因为我们为每个子元素设置了flex: 1。进一步配置Flexbox
你可以进一步配置Flexbox的布局属性,例如:
justify-content: 定义在主轴(通常是水平轴)上的子元素的排列方式。align-items: 定义在交叉轴(通常是垂直轴)上的子元素的排列方式。flex-direction: 定义主轴的方向,例如row(默认,水平排列)或column(垂直排列)。
示例:
<style> .parent { display: flex; justify-content: space-around; /* 水平分布 */ align-items: center; /* 垂直居中 */ } .child { flex: 1; padding: 10px; border: 1px solid black; } </style>通过正确地设置
display: flex,你可以利用这些Flexbox属性来实现复杂的布局。