java 实现邮件发送功能
时间: 2023-11-28 09:05:25 浏览: 35
Java 可以使用 JavaMail API 实现邮件发送功能。以下是一个简单的代码示例:
```
import java.util.Properties;
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 MailSender {
public static void main(String[] args) {
final String username = "your-email@example.com"; // 替换为你的邮箱用户名
final String password = "your-password"; // 替换为你的邮箱密码
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.example.com"); // 替换为你的 SMTP 服务器地址
props.put("mail.smtp.port", "587"); // 替换为你的 SMTP 端口号
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email@example.com")); // 替换为你的发件人邮箱地址
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient-email@example.com")); // 替换为你的收件人邮箱地址,多个邮箱地址用逗号分隔
message.setSubject("Test Email");
message.setText("This is a test email sent from Java.");
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```