简体   繁体   English

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

[英]Java Mail API - can't send email

I am trying to send an email using the Java Mail API like this: 我正在尝试使用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();
    }
}

but I am getting the following exception: 但我收到以下异常:

在此处输入图片说明

Remember to check that you have a SMTP server on some_host:25. 记住要检查some_host:25上是否有SMTP服务器。 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) 您永远不会直接发送邮件,而是通过邮件服务器发送邮件,邮件服务器会保持队列并中继到接收邮件服务器(例如gmail,hotmail等)

You can use Fake Sendmail or sendmail itself if you're on unix-like terminal 如果您使用的是类似Unix的终端,则可以使用Fake Sendmail或sendmail本身

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 和您的* .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
  • Here I use google SMTP server, so for using that one you should have a mailbox in gmail 我在这里使用Google SMTP服务器,因此要使用该服务器,您应该在gmail中有一个邮箱

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM