【发布时间】:2013-02-07 23:01:49
【问题描述】:
我正在尝试从我的 Java 代码发送电子邮件。我正在使用 javax.mail 库。 这是我的代码:
public class SendMail {
public void postMail(final String recipients, final String subject, final String message) throws MessagingException {
boolean debug = false;
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "gmail-smtp.l.google.com");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
try {
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress("me@gmail.com");
msg.setFrom(addressFrom);
InternetAddress addressTo = new InternetAddress(recipients);
msg.setRecipient(Message.RecipientType.TO, addressTo);
msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
} catch (MessagingException e) {
System.out.println("SendMail:postMail - " + e.getMessage() + "; " + e.getCause());
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username@gmail.com", "password");
}
}
}
一切正常,但是当收件人收到邮件时,发件人不是我指定的发件人,而是我用于身份验证的发件人。所以在这种情况下,发件人是“username@gmail.com”而不是我用于指令 message.setFrom 的“me@gmail.com”。
有谁知道怎么回事?
【问题讨论】:
-
如果您想发送一封有其他发件人而不是您发送的帐户的邮件,您需要使用允许相同的 smtp 服务器。 Google 使用身份验证来防止人们使用不存在的邮件 ID 发送电子邮件。因此,即使您设置了发件人 xyz@gmail.com,也会使用您的原始邮件 ID。
-
好的,也许我会更换供应商。谢谢@Logan
标签: java jakarta-mail