Java Mail API - 无法发送电子邮件

时间:2017-12-21 20:47:05

标签: java email javamail

我正在尝试使用Java Mail API发送电子邮件,如下所示:

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();
    }
}

但我收到以下异常:

enter image description here

2 个答案:

答案 0 :(得分:0)

请记住检查some_host上是否有SMTP服务器:25。你永远不会直接发送东西,而是通过邮件服务器,邮件服务器保持队列并转发到接收邮件服务器(例如gmail,hotmail等)

如果您使用类似unix的终端

,则可以使用Fake Sendmail或sendmail本身

答案 1 :(得分:0)

我已经从我的项目中复制了它:

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);

你的* .properties文件应该像

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
  • 这里我使用的是谷歌SMTP服务器,所以要使用那个,你应该在gmail中有一个邮箱