Javaコードから誰かにメールを送信する必要がある場合、メールサーバーの資格情報にアクセスする必要があります。まあ、いつもではない。
Googleは、メールサーバーの1つへの無料アクセスを提供しており、Javaコードで使用できます。私自身へのメモのような場合は、以下の記述コード。したがって、いつか必要になった場合は、ここで参照できます:http : //www.computerbuzz.in/2014/02/how-to-send-email-in-java-using-gmail.html
private void setMailServerProperties()
{
Properties emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", "586");
emailProperties.put("mail.smtp.auth", "true");
emailProperties.put("mail.smtp.starttls.enable", "true");
mailSession = Session.getDefaultInstance(emailProperties, null);
}
private MimeMessage draftEmailMessage() throws AddressException, MessagingException
{
String[] toEmails = { "computerbuzz@gmail.com" };
String emailSubject = "Test email subject";
String emailBody = "This is an email sent by http://www.computerbuzz.in.";
MimeMessage emailMessage = new MimeMessage(mailSession);
/**
* Set the mail recipients
* */
for (int i = 0; i < toEmails.length; i++)
{
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
}
emailMessage.setSubject(emailSubject);
/**
* If sending HTML mail
* */
emailMessage.setContent(emailBody, "text/html");
/**
* If sending only text mail
* */
//emailMessage.setText(emailBody);// for a text email
return emailMessage;
}
private void sendEmail() throws AddressException, MessagingException
{
/**
* Sender's credentials
* */
String fromUser = "user-email@gmail.com";
String fromUserEmailPassword = "*******";
String emailHost = "smtp.gmail.com";
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserEmailPassword);
/**
* Draft the message
* */
MimeMessage emailMessage = draftEmailMessage();
/**
* Send the mail
* */
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
System.out.println("Email sent successfully.");
}
}