是你可以做。
只需调用此函数即可向客户端发送自动电子邮件。 参数“to”是您想要发送电子邮件的电子邮件地址。
附加pdf请参考this tutorial。
我通常在Maven项目中做它。如果您正在使用maven项目,然后导入以下依赖项。 https://mvnrepository.com/artifact/javax.mail/mail/1.4
private void sendMail(String to, String subject, String emailBody) throws MessagingException{
final String username = "[email protected]";
final String password = "emailPassword";
Properties props = new 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.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
感谢您的快速回答!不,我没有使用maven,是否有必要?我运行了你的代码,它给了我一个“** ConnectException:**拒绝连接” – BenSkeleton
我再次搜索了一遍,发现我可以使用mac内置的postfix邮件程序,它可以从终端内启动,只需通过“sudo postfix start ”。它现在工作,非常感谢! – BenSkeleton
@BenSkeleton感谢您的信息。 (Windows用户在这里;)) – arcs