在 Java 中发送邮件通常使用 JavaMail API。以下是使用 JavaMail API 发送邮件的基本步骤:

1. 导入相关的库:

   在项目中导入 JavaMail API 和 Java Activation Framework (JAF) 的库。这两个库包含了发送邮件所需的类和方法。
   <!-- Maven 依赖 -->
   <dependency>
       <groupId>com.sun.mail</groupId>
       <artifactId>javax.mail</artifactId>
       <version>1.6.2</version>
   </dependency>
   <dependency>
       <groupId>javax.activation</groupId>
       <artifactId>activation</artifactId>
       <version>1.1.1</version>
   </dependency>

2. 编写邮件发送代码:
   import javax.mail.*;
   import javax.mail.internet.InternetAddress;
   import javax.mail.internet.MimeMessage;
   import java.util.Properties;

   public class EmailSender {
       public static void main(String[] args) {
           // 1. 设置邮件发送相关属性
           Properties properties = new Properties();
           properties.put("mail.smtp.host", "smtp.example.com");
           properties.put("mail.smtp.port", "587");
           properties.put("mail.smtp.auth", "true");
           properties.put("mail.smtp.starttls.enable", "true");

           // 2. 创建会话对象
           Session session = Session.getInstance(properties, new Authenticator() {
               @Override
               protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication("your_email@example.com", "your_password");
               }
           });

           try {
               // 3. 创建邮件消息
               Message message = new MimeMessage(session);
               message.setFrom(new InternetAddress("your_email@example.com"));
               message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
               message.setSubject("Test Email");
               message.setText("This is a test email from Java.");

               // 4. 发送邮件
               Transport.send(message);

               System.out.println("Email sent successfully!");

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

   替换代码中的 "smtp.example.com"、"your_email@example.com"、"your_password"、"recipient@example.com" 分别为你的 SMTP 服务器地址、发件人邮箱、发件人密码、收件人邮箱。

   注意:在实际项目中,建议使用安全的方式存储和管理邮件用户名和密码,避免直接在代码中硬编码。

3. 授权邮件发送者:

   如果你的邮箱开启了两步验证或应用密码,需要使用应用密码或授权码来代替邮箱密码。

   - 对于 Gmail,需要在账户设置中生成应用密码。
   - 对于其他邮箱,可能需要开启客户端授权。

以上就是使用 JavaMail API 发送邮件的基本步骤。请确保在使用该代码时遵循相关的法规和服务提供商的使用规定,以免触发滥用行为。


转载请注明出处:http://www.pingtaimeng.com/article/detail/13499/Java