I'm trying to send email from my Java code. I'm using the javax.mail library. This is my code:
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");
}
}
}
Everything worsk fine but when recipients recive the message, the sender is not the one I specified but the one I used for the authentication. So in this case, the sender is "username@gmail.com" instead of "me@gmail.com" that I used for the instruction message.setFrom.
Does anyone know what is wrong?
you can try to add
props.put("mail.from", "me@gmail.com");
Which is used not in the message but at the beginning of the SMTP Transaction.
See http://www.tcpipguide.com/free/t_SMTPMailTransactionProcess-3.htm
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.