跳至主要內容

发送邮件


以下是使用 Java 发送邮件的简单示例代码,它使用了 JavaMail API:

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class EmailSender {

    public static void main(String[] args) {

        // 发件人邮箱地址
        String fromEmail = "your_email@example.com";
        // 发件人邮箱密码(如果是第三方客户端授权登录,需要填写授权码)
        String password = "your_email_password";
        // 收件人邮箱地址
        String toEmail = "recipient_email@example.com";
        // SMTP 服务器地址
        String smtpHost = "smtp.example.com";

        // 设置邮件属性
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.port", "587");

        // 创建会话对象
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, password);
            }
        });

        try {
            // 创建邮件消息对象
            MimeMessage message = new MimeMessage(session);
            // 设置发件人
            message.setFrom(new InternetAddress(fromEmail));
            // 设置收件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            // 设置邮件主题
            message.setSubject("Java Mail Test");
            // 设置邮件内容
            message.setText("This is a test email sent from Java.");

            // 发送邮件
            Transport.send(message);
            System.out.println("Email sent successfully.");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,你需要替换以下内容:

  • fromEmail:发件人的邮箱地址。
  • password:发件人邮箱的密码或者授权码(如果是使用第三方客户端授权登录)。
  • toEmail:收件人的邮箱地址。
  • smtpHost:SMTP 服务器地址,通常是你的邮箱提供商提供的。

请确保你的电子邮箱允许使用 SMTP 协议发送邮件,有些邮箱服务提供商需要在设置中启用 SMTP 服务,并且可能需要进行额外的配置。

上次编辑于: