Servlet 发送电子邮件


Servlet 发送电子邮件

Servlet 是运行在服务器端的 Java 程序,因此可以很方便地发送电子邮件。本文将介绍如何在 Servlet 中使用 JavaMail API 发送电子邮件,包括配置 SMTP 服务器、创建邮件、发送邮件等步骤。

配置 SMTP 服务器

在发送邮件之前,需要先配置 SMTP(Simple Mail Transfer Protocol)服务器。SMTP 服务器负责将邮件发送到接收方的邮箱,并提供安全验证等功能。SMTP 服务器的地址和端口号可以从电子邮件服务提供商处获得。

下面是一个示例代码,展示了如何创建一个 SMTPSession 对象,它包含了发送邮件所需的参数:

String host = "smtp.gmail.com";
int port = 587;
String username = "your-email-address";
String password = "your-email-password";

Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);

Session session = Session.getInstance(props,
  new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
});

上面的代码中,需要提供 SMTP 服务器的地址和端口号、发件人的邮箱地址和密码。还需要设置邮件客户端使用 STARTTLS 进行安全加密、使用登录验证等信息。

创建邮件

创建一封邮件需要指定邮件的发送者、接收者、主题、内容等信息。下面是一个示例代码,展示了如何创建一封邮件:

String to = "recipient@example.com";
String from = "sender@example.com";
String subject = "Important email";
String body = "This is an important email from my Servlet application.";

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
  InternetAddress.parse(to));
message.setSubject(subject);
message.setText(body);

上面的代码中,指定了收件人的邮箱地址、发件人的邮箱地址、邮件主题和内容。邮件的内容可以是纯文本或者HTML格式。

发送邮件

最后一步是发送邮件。在 JavaMail API 中,发送一封邮件只需要调用Transport.send() 方法即可。

下面是一个示例代码:

Transport.send(message);

完整的示例代码如下所示:

String host = "smtp.gmail.com";
int port = 587;
String username = "your-email-address";
String password = "your-email-password";

Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);

Session session = Session.getInstance(props,
  new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
});

String to = "recipient@example.com";
String from = "sender@example.com";
String subject = "Important email";
String body = "This is an important email from my Servlet application.";

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
  InternetAddress.parse(to));
message.setSubject(subject);
message.setText(body);

Transport.send(message);

这样,在发送电子邮件的时候,Servlet 就可以方便地调用 JavaMail API 进行操作了。