21xrx.com
2025-03-26 19:47:44 Wednesday
文章检索 我的文章 写文章
Java实现邮件发送功能代码
2023-06-16 06:16:53 深夜i     6     0
JavaMail API

Java是一种功能强大的编程语言,它可以用来开发各种各样的应用程序,包括邮件发送功能。在本文中,我们将讨论如何使用Java编写一个简单的邮件发送程序。

首先,我们需要导入JavaMail API。该API是一个开源的Java邮件客户端库,可用于发送和接收电子邮件。我们需要将此API添加到我们的项目中,以便我们可以使用它来发送邮件。

接下来,我们需要配置SMTP服务器。SMTP(Simple Mail Transfer Protocol)是一种Internet标准协议,用于发送和接收电子邮件。我们需要提供SMTP服务器的主机名和端口号,以及发件人和收件人的电子邮件地址。

最后,我们可以编写Java代码来实现邮件发送功能。以下是一个简单示例:

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender {
 public static void main(String[] args) {
  String host = "smtp.gmail.com";
  int port = 587;
  String username = "your_email@gmail.com";
  String password = "your_email_password";
  String recipient = "recipient_email@example.com";
  Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.port", port);
  Session session = Session.getInstance(props, new javax.mail.Authenticator() {
   protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
    return new javax.mail.PasswordAuthentication(username, password);
   }
  });
  try {
   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress(username));
   message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
   message.setSubject("Testing Subject");
   message.setText("Hello World!");
   Transport.send(message);
   System.out.println("Mail sent successfully");
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}

以上代码将发送一封标题为“Testing Subject”,正文为“Hello World!”的电子邮件到recipient_email@example.com。

,SMTP服务器,邮件发送

  
  

评论区