使用Java程序发送电子邮件
无论您使用的是Java、JavaEE、 Python等平台,发送电子邮件都是一项基本要求。发送电子邮件可能需要发送错误警报或确认注册或注册。 Java通过编写Java程序提供了发送电子邮件的功能。
要使用Java发送电子邮件,您需要三件事:
- JavaMail API
- Java激活框架 (JAF)
- 您的 SMTP 服务器详细信息
您可以从Java官方网站下载最新版本的 JavaMail API 和 JAF。成功下载这两个后,解压。在您的类路径中添加mail.jar 、 smtp.jar和activation.jar文件,以便有资格发送电子邮件。
添加这些文件后,按照以下步骤编写一个Java程序来发送电子邮件:
- 通过调用 getDefaultInstance() 方法并将属性作为参数传递来创建一个新的会话对象,以获取所有重要的属性,如 SMTP 服务器的主机名等。
- 通过传递在上一步中创建的会话对象来创建一个 MimeMessage 对象。
- 最后一步是使用 javax.mail.Transport 发送电子邮件
Java
// Java program to send email
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
public class SendEmail
{
public static void main(String [] args)
{
// email ID of Recipient.
String recipient = "recipient@gmail.com";
// email ID of Sender.
String sender = "sender@gmail.com";
// using host as localhost
String host = "127.0.0.1";
// Getting system properties
Properties properties = System.getProperties();
// Setting up mail server
properties.setProperty("mail.smtp.host", host);
// creating session object to get properties
Session session = Session.getDefaultInstance(properties);
try
{
// MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From Field: adding senders email to from field.
message.setFrom(new InternetAddress(sender));
// Set To Field: adding recipient's email to from field.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
// Set Subject: subject of the email
message.setSubject("This is Subject");
// set body of the email.
message.setText("This is a test mail");
// Send email.
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
Java
// create a new String array
String[] recipients = new String[4];
// add email addresses
recipients[0] = first@gmail.com
recipients[1] = second@gmail.com
recipients[2] = third@gmail.com
recipients[3] = fourth@gmail.com
// inside of try block instead of using addRecipient()
// use addRecipients()
// specify the type of field(TO, CC ,BCC)
// pass the array of email ids of recipients
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Java
// Java program to send email
// with HTML templates
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
public class SendEmail
{
public static void main(String [] args)
{
// email ID of Recipient.
String recipient = "recipient@gmail.com";
// email ID of Sender.
String sender = "sender@gmail.com";
// using host as localhost
String host = "127.0.0.1";
// Getting system properties
Properties properties = System.getProperties();
// Setting up mail server
properties.setProperty("mail.smtp.host", host);
// creating session object to get properties
Session session = Session.getDefaultInstance(properties);
try
{
// MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From Field: adding senders email to from field.
message.setFrom(new InternetAddress(sender));
// Set To Field: adding recipient's email to from field.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
// Set Subject: subject of the email
message.setSubject("This is Subject");
// set body of the email.
message.setContent("This is a HTML text
","text/html");
// Send email.
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
CPP
// Java program to send email
// with attachments
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
public class SendEmail
{
public static void main(String [] args)
{
// email ID of Recipient.
String recipient = "recipient@gmail.com";
// email ID of Sender.
String sender = "sender@gmail.com";
// using host as localhost
String host = "127.0.0.1";
// Getting system properties
Properties properties = System.getProperties();
// Setting up mail server
properties.setProperty("mail.smtp.host", host);
// creating session object to get properties
Session session = Session.getDefaultInstance(properties);
try
{
// MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From Field: adding senders email to from field.
message.setFrom(new InternetAddress(sender));
// Set To Field: adding recipient's email to from field.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
// Set Subject: subject of the email
message.setSubject("This is Subject");
// creating first MimeBodyPart object
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is body of the mail");
// creating second MimeBodyPart object
BodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "attachment.txt"
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
// creating MultiPart object
Multipart multipartObject = new MimeMultipart();
multipartObject.addBodyPart(messageBodyPart1);
multipartObject.addBodyPart(messageBodyPart2);
// set body of the email.
message.setContent(multipartObject);
// Send email.
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
输出:
Mail successfully sent
向多个收件人发送电子邮件
向多个收件人发送电子邮件与向单个收件人发送电子邮件相同。不同之处在于,要将邮件发送给多个收件人,您应该添加多个收件人。要添加多个收件人,我们必须调用以下方法并将收件人类型和电子邮件地址列表作为参数传递:
void addRecipients(Message.RecipientType type, Address[] addresses)
throws MessagingException
{
}
要在“收件人”字段中添加电子邮件,您可以使用 Message.RecipientType.To 。同样,要在“CC”和“BCC”字段中添加电子邮件,您必须使用 Message.RecipientType.CC 和 Message.RecipientType.BCC。
上述方法中的参数地址是一个包含所有电子邮件 ID 列表的数组。您必须使用 InternetAddress() 方法来指定电子邮件。
假设您要向 4 个人发送电子邮件。您必须创建一个大小为 4 的字符串数组并将收件人的电子邮件地址存储在其中。按照上面的程序发送一封简单的电子邮件,而不是添加单个收件人,而是使用 addRecipients 方法添加多个收件人,如下所示:
Java
// create a new String array
String[] recipients = new String[4];
// add email addresses
recipients[0] = first@gmail.com
recipients[1] = second@gmail.com
recipients[2] = third@gmail.com
recipients[3] = fourth@gmail.com
// inside of try block instead of using addRecipient()
// use addRecipients()
// specify the type of field(TO, CC ,BCC)
// pass the array of email ids of recipients
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
使用 HTML 模板发送电子邮件
有时电子邮件是使用 HTML 模板发送的,即电子邮件的正文是用 HTML 编写的。这使得电子邮件格式良好且外观精美。使用 HTML 模板发送电子邮件的程序与发送普通电子邮件的程序几乎相同。不同之处在于,我们必须使用setContent()方法而不是setText()方法来指定电子邮件的正文,并且在setContent()方法中,我们必须将第二个参数指定为“text/html”,第一个参数将是HTML 代码。现在让我们看一下使用 HTML 模板发送电子邮件的程序:
Java
// Java program to send email
// with HTML templates
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
public class SendEmail
{
public static void main(String [] args)
{
// email ID of Recipient.
String recipient = "recipient@gmail.com";
// email ID of Sender.
String sender = "sender@gmail.com";
// using host as localhost
String host = "127.0.0.1";
// Getting system properties
Properties properties = System.getProperties();
// Setting up mail server
properties.setProperty("mail.smtp.host", host);
// creating session object to get properties
Session session = Session.getDefaultInstance(properties);
try
{
// MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From Field: adding senders email to from field.
message.setFrom(new InternetAddress(sender));
// Set To Field: adding recipient's email to from field.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
// Set Subject: subject of the email
message.setSubject("This is Subject");
// set body of the email.
message.setContent("This is a HTML text
","text/html");
// Send email.
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
输出:
Mail successfully sent
发送带附件的电子邮件
JavaMail API 允许您发送包含附件的电子邮件。要发送带有附件的电子邮件,我们必须创建两个 MimeBodyPart 对象并将文本分配给一个对象,并将数据处理程序分配给另一个对象。下面简要描述发送带附件的电子邮件的过程:
- 创建一个新的会话对象
- 创建一个 MimeBodyPart 对象并为其分配文本
- 创建一个新的 MimeBodyPart 对象并将 DataHandler 对象分配给它
- 创建一个 MultiPart 对象并将两个 MimeBodyPart 对象分配给此 MultiPart 对象
- 将此 MultiPart 对象设置为 message.SetContent() 方法。
- 使用 Transport() 方法发送邮件
现在让我们看一下执行此操作的程序:
CPP
// Java program to send email
// with attachments
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
public class SendEmail
{
public static void main(String [] args)
{
// email ID of Recipient.
String recipient = "recipient@gmail.com";
// email ID of Sender.
String sender = "sender@gmail.com";
// using host as localhost
String host = "127.0.0.1";
// Getting system properties
Properties properties = System.getProperties();
// Setting up mail server
properties.setProperty("mail.smtp.host", host);
// creating session object to get properties
Session session = Session.getDefaultInstance(properties);
try
{
// MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From Field: adding senders email to from field.
message.setFrom(new InternetAddress(sender));
// Set To Field: adding recipient's email to from field.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
// Set Subject: subject of the email
message.setSubject("This is Subject");
// creating first MimeBodyPart object
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is body of the mail");
// creating second MimeBodyPart object
BodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "attachment.txt"
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
// creating MultiPart object
Multipart multipartObject = new MimeMultipart();
multipartObject.addBodyPart(messageBodyPart1);
multipartObject.addBodyPart(messageBodyPart2);
// set body of the email.
message.setContent(multipartObject);
// Send email.
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
输出:
Mail successfully sent