【发布时间】:2021-05-17 06:23:12
【问题描述】:
我用 javax.mail 库写了一个 emailSender。我不知道我的错误在哪里,因为在视频中代码是从哪里工作的。
视频:https://www.youtube.com/watch?v=bkpHQD9e5hc&t=1630s
我还在这个网站上看到了关于这个主题的另一个问题,但这些问题的解决方案都没有解决我的问题
代码:
public class MailSender {
protected Session mailSession;
public void login(String smtpHost, String smtpPort, String username, String password) {
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.socketFactory.port", smtpPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", smtpPort);
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
this.mailSession = Session.getDefaultInstance(props, auth);
System.out.println("Eingeloggt.");
}
public void send(String senderMail, String senderName, String receiverAddresses, String subject, String message, String username, String password)
throws MessagingException, IllegalStateException, UnsupportedEncodingException {
if (mailSession == null) {
throw new IllegalStateException("Du musst dich zuerst einloggen (login()-Methode)");
}
MimeMessage msg = new MimeMessage(mailSession);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(senderMail, senderName));
msg.setReplyTo(InternetAddress.parse(senderMail, false));
msg.setSubject(subject, "UTF-8");
msg.setText(message, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiverAddresses, false));
System.out.println("Versende E-Mail...");
Transport.send(msg, username, password);
System.out.println("E-Mail versendet.");
}
}
【问题讨论】:
标签: java email smtp smtpclient