最近使用commons mail进行发送HTML邮件时碰到一些问题,记录下解题思路。
1. 发送HTML邮件
import org.apache.commons.mail.HtmlEmail; ... // Create the email message HtmlEmail email = new HtmlEmail(); email.setHostName("mail.myserver.com"); email.addTo("jdoe@somewhere.org", "John Doe"); email.setFrom("me@apache.org", "Me"); email.setSubject("Test email with inline image"); // embed the image and get the content id URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif"); String cid = email.embed(url, "Apache logo"); // set the html message email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>"); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send();
需要注意的配置是:
email.setHostName("smtp.office365.com"); email.setSmtpPort(587);
smtp服务器的地址和端口, 比如smtp.office365.com; 这个需要查询你的邮件服务提供商。
email.setAuthentication(new DefaultAuthenticator(username, password));
第二个配置是登录到服务器的用户名和密码,这样就能发送邮件了。
2. 在我本地测试的时候,使用自己的用户名和密码进行登录发送邮件OK,但是部署到Spark集群时报Authentication Fail的错误。
想了半天没有结果,过了一阵公司安全部门发了询问我的邮件账号登录异常。终于找到原因了,原来公司集群里进行了邮件登录限制。查询集群发送邮件的相关配置。
在Clouera Manage Configuration 页面进行搜索 ”oozie_email_smtp“ 可以获得host, port, username, password 相关信息。
OK,用服务器上的配置替换到相应位置数据即可。