21xrx.com
2025-03-24 05:48:58 Monday
文章检索 我的文章 写文章
使用Java Mail向邮箱发送邮件
2023-06-12 10:28:13 深夜i     11     0
Java Mail

在日常工作中,我们常常需要使用邮件发送功能将重要信息发送给用户。Java Mail是一个很好的Java库,它提供了发送和接收邮件的API。下面我们来看一下使用Java Mail向邮箱发送邮件的代码实现。

代码实现:

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
  public static void main(String[] args) throws MessagingException {
   
    // SMTP server information
    String host = "smtp.gmail.com";
    String port = "587";
    String mailFrom = "your-email@gmail.com";
    String password = "your-email-password";
    // outgoing message information
    String mailTo = "companion@example.com";
    String subject = "Email test";
    String message = "Hello, this is a testing message!";
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
      public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(mailFrom, password);
      }
    };
    
    Session session = Session.getInstance(properties, auth);
    // creates message
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(mailFrom));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setText(message);
    // sends the message
    Transport.send(msg);
    
    System.out.println("Email sent successfully!");
  }
}

这段代码可以将邮件发送到指定的邮箱地址。需要注意的是,邮件服务商需要支持SMTP协议才能使用Java Mail发送邮件。如果您使用的是Gmail,可以使用上面提供的代码进行测试。您只需要将mailFrom和password更改为您自己的Gmail账户信息即可。

、邮件发送、API

  
  

评论区