以下内容引用自http://wiki.jikexueyuan.com/project/java/sending-email.html

用Java应用程序来发送一封电子邮件是足够简单的,但是开始时应该在机器上安装有JavaMail API和Java Activation Framework(JAF)。

下载并解压这些文件,在新创建的顶级目录中将找到许多应用程序的jar文件。需要CLASSPATH中添加mail.jar和activation.jar文件。(POM项目和Eclipse工程省略这一步)

一、发送一封简单的电子邮件

这是从机器中发送一封简单的电子邮件的例子。这里假设本地主机连接到了因特网并且能够发送一封电子邮件。

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*; public class SendEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned
String from = "web@gmail.com"; // Assuming you are sending email from localhost
String host = "localhost";//This is SMTP Server,Ex:smtp.163.com // set email username
String user = "user"; // set email password
String password = "password"; // Get system properties
Properties properties = System.getProperties(); // Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.user", user);
properties.setProperty("mail.password", password); // Get the default Session object.
Session session = Session.getDefaultInstance(properties); try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session); // Set From: header field of the header.
message.setFrom(new InternetAddress(from)); // Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field
message.setSubject("This is the Subject Line!"); // Now set the actual message
message.setText("This is actual message"); // Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
//编译并运行这个程序来发送一封简单的电子邮件:
$ java SendEmail
Sent message successfully....

如果想要给多个收信者发送一封电子邮件,那么以下的方法将被用来发送给指定的多个电子邮件ID:

void addRecipients(Message.RecipientType type,  Address[] addresses) throws MessagingException

这是参数的描述:

  • type:这将被设置为TO,CC或者BCC。这里CC表示副本,BCC表示Black Carbon Copy。例如Message.RecipientType.TO。
  • addresses:这是电子邮件ID的数组。当指定电子邮件ID时,需要使用InternetAddress()。

二、发送一封HTML电子邮件

这是从机器发送一封HTML电子邮件的例子。这里假设本地主机连接到了因特网并且能够发送一封电子邮件。

这个例子和前一个非常相似,除了在这用setContent()方法来设置第二个参数为"text/html"以指定 HTML 内容被包括在消息中的内容。

使用这个例子,可以发送任何HTML内容。

//File Name SendHTMLEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*; public class SendHTMLEmail {
public static void main(String[] args) { // Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned
String from = "web@gmail.com"; // Assuming you are sending email from localhost
String host = "localhost";//This is SMTP Server,Ex:smtp.163.com // set email username
String user = "user"; // set email password
String password = "password"; // Get system properties
Properties properties = System.getProperties(); // Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.user", user);
properties.setProperty("mail.password", password); // Get the default Session object.
Session session = Session.getDefaultInstance(properties); try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session); // Set From: header field of the header.
message.setFrom(new InternetAddress(from)); // Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field
message.setSubject("This is the Subject Line!"); // Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message</h1>", "text/html"); // Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
//编译并运行这个程序来发送一封 HTML 的电子邮件:
$ java SendHTMLEmail
Sent message successfully....

三、发送电子邮件中的附件

这是一个从机器中发送一封带有附件的电子邮件的例子。这里假设本地主机连接到了因特网并且能够发送一封电子邮件。

//File Name SendFileEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*; public class SendFileEmail {
public static void main(String[] args) { // Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned
String from = "web@gmail.com"; // Assuming you are sending email from localhost
String host = "localhost";// This is SMTP Server,Ex:smtp.163.com // set email username
String user = "user"; // set email password
String password = "password"; // Get system properties
Properties properties = System.getProperties(); // Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.user", user);
properties.setProperty("mail.password", password); // Get the default Session object.
Session session = Session.getDefaultInstance(properties); try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session); // Set From: header field of the header.
message.setFrom(new InternetAddress(from)); // Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field
message.setSubject("This is the Subject Line!"); // Create the message part
BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message
messageBodyPart.setText("This is message body"); // Create a multipar message
Multipart multipart = new MimeMultipart(); // Set text message part
multipart.addBodyPart(messageBodyPart); // Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart); // Send the complete message parts
message.setContent(multipart); // Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
//编译并运行这个程序来发送一封 HTML 电子邮件:
$ java SendFileEmail
Sent message successfully....

四、用户身份认证部分

如果为了身份认证的目的需要给电子邮件服务器提供用户ID和密码,可以像这样设置这些属性:

 props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");

电子邮件发送机制的剩余部分和上述解释的一样。

测试工程:https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test27

最新文章

  1. System.Web.HttpRequestValidationException: A potentially dangerous Request.F
  2. 使用独立模式安装Sharepoint Server 2013出现创建示例数据错误的解决方案
  3. Ajax最详细的参数解析和场景应用
  4. inverse理解
  5. 关于API认证的问题
  6. 济南学习D2T2__数学分析题
  7. 华为访问列表traffic-policy案例
  8. 20145215实验五 Java网络编程及安全
  9. [每日一题] 11gOCP 1z0-053 :2013-10-11 Flashback Data Archive属性.........................43
  10. ExtJs4.2 知识点
  11. less学习-浏览器端编译(一)
  12. iOS-点击视图,视图背景颜色随机更改
  13. WPF那些事儿
  14. 3.移植驱动到3.4内核-移植DM9000C驱动
  15. BZOJ 2806: [Ctsc2012]Cheat [广义后缀自动机 单调队列优化DP 二分]
  16. java eclipse中使用wsdl生成soap 的客户端代码
  17. linux 命令 — find
  18. react-踩坑记录——Link带参数跳转后this.props为空对象
  19. 搭建简单SBT工程实践
  20. 37.scrapy解决翻页及采集杭州造价网站材料数据

热门文章

  1. mysqldump 使用详解
  2. 7-Java-C(小题答案)
  3. Django的架构
  4. vscode 打开新文件不替换旧文件
  5. java+selenium+maven+IntelliJ IDEA 搭建简单的UI自动化测试环境
  6. (9) openssl enc(对称加密)
  7. c++_方格分割
  8. BeautifulSoup与aiohttp的简单应用-爬取《网上中华五千年》音频
  9. C语言学习11
  10. php 链接 mongodb