Javaでメール送信機能
サンプルコード
<%@ page import=”java.util.*”%>
<%@ page import=”javax.mail.*”%>
<%@ page import=”javax.mail.internet.*”%>
<%@ page import=”javax.activation.*”%>
<%
// SMTP サーバー情報
String host = “smtp.gmail.com”;
int port = 587;
String username = “your-email@gmail.com”;
String password = “your-password”;
// アドレス情報
String from = “your-email@gmail.com”;
String to = “recipient-email@example.com”;
String subject = “Test Email”;
String content = “This is a test email.”;
// SMTP サーバー認証設定
Properties props = new Properties();
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.starttls.enable”, “true”);
props.put(“mail.smtp.host”, host);
props.put(“mail.smtp.port”, port);
// SMTP セッション設定
Session mailSession = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 内容
Message message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
message.setSubject(subject);
message.setText(content);
// Transport.send(message);
out.println(“Email sent successfully.”);
} catch (MessagingException e) {
out.println(“Failed to send email. Error message: ” + e.getMessage());
}
%>