在Java SE平台之外(但包含在JavaEE中), JavaMail软件包提供了一个用于构建邮件和消息传递应用程序的平台。 让我们举一个例子。
发送一条简单的短信
// Common variables
String host = "your_smtp_server";
String from = "from_address";
String to = "to_address";// Set properties
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.debug", "true");// Get session
Session session = Session.getInstance(props);try {// Instantiate a messageMessage msg = new MimeMessage(session);// Set the FROM messagemsg.setFrom(new InternetAddress(from));// The recipients can be more than one so we use an array but you can// use 'new InternetAddress(to)' for only one address.InternetAddress[] address = {new InternetAddress(to)};msg.setRecipients(Message.RecipientType.TO, address);// Set the message subject and date we sent it.msg.setSubject("Email from JavaMail test");msg.setSentDate(new Date());// Set message contentmsg.setText("This is the text for this simple demo using JavaMail.");// Send the messageTransport.send(msg);
}
catch (MessagingException mex) {mex.printStackTrace();
}
或者,改为使用:
msg.setText("This is the text for this simple demo using JavaMail.");
您可以使用next设置消息内容:
msg.setContent("This is the text for this simple demo using JavaMail.", "text/plain");
检查电子邮件地址
这是一个使用正则表达式检查电子邮件格式是否正确的小技巧:
Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
if(rfc2822.matcher(EMAIL_ADDRESS).matches()) {// Well formed email
}
多部分消息
很好,但是通常您不会发送简单的短信。 相反,您发送带有粗体或斜体文本,图像等的漂亮HTML正文消息。
注意:请参阅下面的“参考”部分,以了解有关MIME格式的信息,该格式扩展了您可以附加到电子邮件的数据的范围,以允许多部分,附件等。
编写多部分消息时,内容由不同部分组成,例如,一部分是作为简单文本编写的消息,另一部分是使用HTML以增强方式编写的同一消息。 然后,读取消息的客户端负责根据其功能来渲染适当的部分。
...
// Here create two parts and set as message contect
// Create and fill first part
MimeBodyPart part1 = new MimeBodyPart();
part1.setText("This is part one of this multipart message.");// Create and fill second part
MimeBodyPart part2 = new MimeBodyPart();
part2.setText("This is part two of this multipart message.");// Create the Multipart.
Multipart mp = new MimeMultipart();
mp.addBodyPart(part1);
mp.addBodyPart(part2);// Set the message's content
msg.setContent(mp);
...
发送附件
太棒了,我们知道如何发送纯文本电子邮件以及更令人难以置信的内容,例如包含HTML内容的多部分消息。 下一步是发送附加了太多文件的电子邮件。
创建带有附件的电子邮件类似于创建多部分邮件,其中一部分可以是邮件的文本,另一部分可以是附件。 秘密在接下来的几行中:
...
// Create a new part for the attached file
MimeBodyPart part3 = new MimeBodyPart();// Put a file in the second part
FileDataSource fds = new FileDataSource("THE_FILE_NAME");
part3.setDataHandler(new DataHandler(fds));
part3.setFileName(fds.getName());// 'mp' is the previously created 'MimeMultipart' object
mp.addBodyPart(part3);// 'msg' is the previously created 'Message' object
msg.setContent(mp);
...
HTML消息
创建带有HTML内容的多部分消息非常简单,只需在setContent方法中指定MIME类型即可:
...
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>Sample</h1><p>This is a sample HTML part</p>", "text/html");
...
在HTML代码中附加图像
如果您使用HTML编写丰富的消息,则可以使用'img'标签添加图像。 如果从外部服务器引用了图像,则没有问题,但是:如何将图像附加到消息并在HTML消息正文中进行呈现?
想法如下:
- 首先,您需要附加图片文件并设置一个标识符,然后
- 其次,您需要编写HTML代码并在“ img”标签中引用图片标识符。
...
// Create and fill html part
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>Sample</h1><p>This is a sample HTML part with an attached image</p>" +"<img src='cid:some_image_id'>", "text/html");// Create a new part for the attached image and set the CID image identifier
MimeBodyPart imagePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("THE_IMAGE_FILE_NAME");
imagePart.setDataHandler(new DataHandler(fds));
imagePart.setHeader("Content-ID", "some_image_id");mp.addBodyPart(htmlPart);
mp.addBodyPart(imagePart);
...
还有什么要说的吗?
至此,您几乎是发送电子邮件的高手。 您知道如何发送简单的电子邮件,具有最丰富HTML内容的多部分电子邮件以及如何在邮件中附加文件和图像。
程序员还能期望什么?
可能是更易于使用的API,这就是Apache Commons Email项目为您提供的。 请参阅“用户指南”部分http://commons.apache.org/email/userguide.html以了解我的意思。 它提供了一个更抽象的API,它比协议更接近人类。
资源资源
- JavaMail – JavaMail项目主页。
- Apache Commons Email – Apache Commons子项目,用于简化JavaMail API的使用方式。 请参阅“ 用户指南 ”部分。
- MIME(多用途Internet邮件扩展名) –多部分电子邮件的MIME格式说明。
参考:在“ A Curious Animal”博客上从我们的JCG合作伙伴 Antonio Santiago 发送Java电子邮件 。
- Spring,Quartz和JavaMail集成教程
- 使用Spring使用Java发送电子邮件– GMail SMTP服务器示例
- Spring MVC3 Hibernate CRUD示例应用程序
- Spring MVC开发–快速教程
- Java教程和Android教程列表
翻译自: https://www.javacodegeeks.com/2011/10/sending-emails-with-java.html