Javaでメール送信のコードを書く方法は?

JavaMailライブラリを使用すればメール送信を実現したJavaのコードを作成できます。以下に簡単なサンプルコードを示します。

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) {
// 发送方邮箱地址
String fromEmail = "your_email@example.com";
// 发送方邮箱密码或授权码
String password = "your_password";
// 接收方邮箱地址
String toEmail = "recipient_email@example.com";
// 配置SMTP服务器的属性
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// 创建Session对象
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
});
try {
// 创建MimeMessage对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(fromEmail));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
// 设置邮件主题
message.setSubject("Test Email");
// 设置邮件内容
message.setText("This is a test email.");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

メールアドレス、パスワード、SMTPサーバーアドレス、受信者アドレスの「your_email@example.com」,「your_password」,「smtp.example.com」,「recipient_email@example.com」を適宜置換してください。

bannerAds