如何使用java mail API编写邮件应用程序,该邮件应用程序一直在glassfish服务器上运行,并在数据库中搜索特定时间并在那时发送邮件。我有用JSF编写的Web应用程序,需要在数据库中给出的特定时间发送邮件。
答案 0 :(得分:1)
对于gmail,请使用以下代码
import org.apache.commons.mail.*;
public class GmailEmailWorking {
public static void main(String[] args) {
String myEmailId = "xyz@gmail.com";
String myPassword = "password";
String senderId = "xyz@yahoo.com";
try {
MultiPartEmail email = new MultiPartEmail();
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator(myEmailId, myPassword));
email.setDebug(true);
email.setHostName("smtp.gmail.com");
email.setFrom(myEmailId);
email.setSubject("Hi");
email.setMsg("This is a test mail ... :-)\n\nPlease check attachements that I have sent.\n\nThanks,\nFahim");
email.addTo(senderId);
email.setTLS(true);
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("/Users/fahadparkar/Desktop/Fahim/tables.xlsx");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Excel");
attachment.setName("tables.xlsx");
email.attach(attachment);
email.send();
System.out.println("Mail sent!");
} catch (Exception e) {
System.out.println("Exception :: " + e);
}
}
}
以下是您需要的jar文件列表
要从其他服务器发送,您需要在以下行进行更改
email.setSmtpPort(587);
email.setHostName("smtp.gmail.com");