I am trying to send an email using the Java Mail API like this:
public static void sendEmail(String to, String from, String msg) {
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject");
message.setText(msg);
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
but I am getting the following exception:
Remember to check that you have a SMTP server on some_host:25. You never send things directly but through a mail server, who keeps a queue and relays to the receiving mail server (eg gmail, hotmail and so on)
You can use Fake Sendmail or sendmail itself if you're on unix-like terminal
I've copied that from my project:
Properties properties = new Properties();
properties.putAll(propertyLoader.getAllProperties());
String senderEmail = properties.getProperty("mail.user");
String senderPswd = properties.getProperty("mail.password");
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, senderPswd);
}
};
Session session = Session.getInstance(properties, auth);
MimeMessage mailMessage = new MimeMessage(session);
mailMessage.setSentDate(dateNow);
Address recipientAddress = new InternetAddress("your_recipient@gmail.com");
mailMessage.setRecipient(Message.RecipientType.TO, recipientAddress);
mailMessage.setSubject("message subject", "UTF-8");
Address senderAddress = new InternetAddress(senderEmail);
mailMessage.setSender(senderAddress);
mailMessage.setContent("here goes message text", "text/html; charset=utf-8");
Transport.send(mailMessage);
And your *.properties file should be like
mail.transport.protocol = smtp
mail.host = smtp.gmail.com
mail.port = 587
mail.port.tls = 587
mail.port.ssl = 465
mail.user = email@gmail.com
mail.password = password
mail.defaultEncoding = UTF-8
mail.smtp.starttls.enable= true
mail.smtp.auth = true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.