我正在尝试使用以下方法发送电子邮件。它工作正常,但我面临一个问题。我想使用不同的“发件人”地址,然后是我用于 gmail 身份验证的地址。所以在下面的代码中,我将“message.setfrom”设置为sender@comp.com,但当接收者收到电子邮件时,发件人地址是user@gmail.com。
请帮助我确定我在这里做错了什么,以及如何将发件人地址正确设置为“sender@comp.com”。感谢你的帮助!谢谢!!
private void sendMail(String textBody, String subject) {
try {
final String messageSender = "user@gmail.com";
final String pass = "pass";
/** get my properties **/
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.debug", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.port", "587");
/** get default session object **/
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(messageSender, pass);
}
});
MimeMessage message = new MimeMessage(session);
String[] to = {"abc@test.com"};
InternetAddress[] addressTo = new InternetAddress[to.length];
message.setRecipients(MimeMessage.RecipientType.TO, addressTo);
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(textBody);
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
message.setFrom(new InternetAddress("sender@comp.com"));
//send message
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}