sav*_*oie 2 java gmail jakarta-mail
我有一个程序,其中有许多用户,每个用户都可以从不同的电子邮件帐户发送电子邮件。
当我尝试使用 JavaMail 发送电子邮件时。它们始终由最先发送电子邮件的用户的帐户发送。
user1 = new User("dummy-email@gmail.com", "dumpass12");
user2 = new User("second-dummy@gmail.com", "secondpass12");
user1.sendMail(toAddress, subject, body);
user2.sendMail(toAddress, subject, body);
Run Code Online (Sandbox Code Playgroud)
现在,当我执行类似的操作时,第二个用户将发送一条消息,但它将来自与 user1 相同的邮箱(即两条消息都来自 dummy-email@gmail.com)。
有人可以向我解释为什么会发生这种情况吗?我必须以某种方式关闭连接吗?我怎样才能发送两封电子邮件并让它们来自不同的帐户?请帮我。
这是我的代码,它实际上发送连接到用户的 Gmail 帐户的电子邮件。
public void sendMail(String toAddress, String subject, String body){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication(getUsername(),getPassword()); }
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(getUsername()));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toAddress));
message.setSubject(subject);
message.setContent(body, "text/html");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Run Code Online (Sandbox Code Playgroud)