On php sending mail is implemented in one line of code! And on java-need 3 weeks ??! (from conversations with developers and managers) |
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.3</version> </dependency>
public class MailSender { public static void sendMail { HtmlEmail email = ... ? email.send();
... <part key="email"> <entry key="hostName">smtp.gmail.com</entry> <entry key="user">sendmail@mycompany.ru</entry> <entry key="password">psw</entry> <entry key="smtpPort">465</entry> <entry key="useSSL">true</entry> <entry key="debug">false</entry> <entry key="charset">UTF-8</entry> <entry key="useTLS">false</entry> </part>
public class MailConfig { public static <T extends Email> T prepareEmail(T email) { email.setHostName(hostName); email.setSmtpPort(port); email.setSSL(useSSL); email.setTLS(useTLS); email.setDebug(debug); email.setAuthenticator(defaultAuthenticator); email.setCharset(charset); return email; }
public class MailServlet extends CommonServlet { @Override protected void doProcess(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) throws IOException, ServletException { String from = ConfigUtil.getProperty("from", params); ... MailSender.sendMail(from, to, cc, ..);
@WebService @SOAPBinding(style = Style.RPC) public interface MailService { @WebMethod public void sendMail( @WebParam(name = "from") String from, @WebParam(name = "to") String to, @WebService(endpointInterface = "mycompany.MailService") public class MailServiceImpl implements MailService { @Override public void sendMail(String from, String to, String cc, String subject, String body, String attachmentUrls) throws StateException { MailSender.sendMailAndRecordHistory(from, to, cc, subject, body, ..); }
<definitions .. targetNamespace="http://mail.mycompany.com/" name="MailServiceImplService"> <message name="sendMail"> <part name="from" type="xsd:string"/> ... <portType name="MailService"> <operation name="sendMail" parameterOrder="from to cc subject body attachmentUrls"> <input wsam:Action="http://mail.mycompany.com/MailService/sendMailRequest" message="tns:sendMail"/> ... <binding name="MailServiceImplPortBinding" type="tns:MailService"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/> <operation name="sendMail"> <soap:operation soapAction=""/> ... <service name="MailServiceImplService"> <port name="MailServiceImplPort" binding="tns:MailServiceImplPortBinding"> <soap:address location="http://mycompany:8080/mail/mailService"/> ...
<listener> <listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class> </listener> <servlet> <servlet-name>mailService</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mailService</servlet-name> <url-pattern>/mailService</url-pattern> </servlet-mapping> <servlet> <servlet-name>mailServlet</servlet-name> <servlet-class>com.mycompany.mail.MailServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> ...
<groupId>com.mycompany</groupId> <artifactId>mail-client</artifactId> <name>Mail Client</name>
MailWSClient.sendMail(...
public class MailWSClient { static String mailWsdl; private static final Service SERVICE; static { URL url = MailWSClient.class.getClassLoader().getResource("mailService.wsdl"); SERVICE = Service.create(url, new QName("http://mail.mycompany.com/", "MailServiceImplService")); // get mail endpoint from config mailWsdl = Config.getUrlAsString("mail/mailService?wsdl"); } public static void sendMail(String from, String to, ..){ getPort().sendMail(from, .. private static MailService getPort() { MailService port = SERVICE.getPort(MailService.class); Map<String, Object> requestContext = ((BindingProvider) port).getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, mailWsdl); return port; }
sendTemplateMail(.., templateKey, params);
static void sendTemplateMail(..., String key, String params) { LOGGER.info("Send template mail from ... String templateUrl = getUrlAsString("template?type=mail&format=html&key=" + key ... MyHttpConnection conn = MyHttpConnection.connect(templateUrl, params); if (conn.isOk()) { String body = conn.getMsg(); sendMail(from, to, cc, MailUtil.getSubject(body), body); } else { throw LOGGER.getStateException(conn.toString(), ExceptionType.TEMPLATE); ...
public class MailUtil { static Pattern MAIL_TITLE = Pattern.compile("<title>(.+)</title>", Pattern.MULTILINE); static String getSubject(String template) { Matcher m = MAIL_TITLE.matcher(template); return m.find() ? m.group(1) : null; }
sendDocMail(String from, String to, String cc, String key, long docId);
public class MailSender { static void sendDocMail(String from, String to, String cc, String key, long docId) throws StateException { List<Attach> list = AttachUtil.getList(docId); MailSender.sendTemplateMailAndRecordHistory(from, to, cc, key, "objectid=" + docId, MailUtil.formatAttach(list)); } public class MailUtil { // format attaches as // ulr1[name1], ulr2[name2], ... static String formatAttach(List<Attach> list) { return Util.collectionToDelimitedString(list, new Presentable<Attach>() { @Override public String toString(Attach attach) { return AttachConfig.downloadUrl + attach.getUuid() + '[' + attach.getName() + ']'; }
CREATE TABLE hist.mail_action ( id SERIAL, _from TEXT, _to TEXT NOT NULL, _cc TEXT, subject TEXT, body TEXT, attachmenturls TEXT, state TEXT NOT NULL, date TIMESTAMP(0) WITHOUT TIME ZONE, key reference.ui_key, params TEXT );
<entry key="scanTodoInterval">30</entry> <entry key="scanFailInterval">600</entry>
scanTodoInterval = ConfigUtil.getInt(SCAN_TODO_INTERVAL, mailProps, 60); // default 60 sec scanFailInterval = ConfigUtil.getInt(SCAN_FAIL_INTERVAL, mailProps, 600); // default 10 min
<listener> <listener-class>com.mycompany.common.web.SchedulerListener</listener-class> </listener>
public class MailWebScanner implements WebScheduler { private final MailScanner todoScanner = new MailScanner("TODO"); private final MailScanner failScanner = new MailScanner("org.apache.commons.mail.EmailException"); @Override public void activate(ServletContext servletContext) { todoScanner.startScanning(MailConfig.scanTodoInterval); failScanner.startScanning(MailConfig.scanFailInterval); } @Override public void deactivate() { todoScanner.deactivate(); failScanner.deactivate(); } @Override public void shutdown() { AsyncExecutor.shutdown(); } } public class MailScanner extends Scanner { private static final BeanListHandler<MailBean> HANDLER = new BeanListHandler<MailBean>(MailBean.class); private final String startWith; public MailScanner(String startWith) { this.startWith = startWith; } void startScanning(int interval) { activate(new Runnable() { @Override public void run() { for (MailBean mail : getMailToSend()) { MailSender.sendTemplateMailAndRecordHistory( } } }, interval, false); } ... List<MailBean> getMailToSend() { return SqlUtil.executeQuery("select * from hist.mail_action where state like '" + startWith + "%'", HANDLER); ...
public class MailWSClient { public static void sendMail(final String from, final String to, final String cc, final String subject, final String body, final String attachmentUrls, boolean async) throws StateException { send(new Runnable() { @Override public void run() { getPort().sendMail(mask(from), mask(to), mask(cc), mask(subject), mask(body), mask(attachmentUrls)); } }, async); } public static void sendTemplateMail(final String from, final String to, final String cc, final String key, final String params, final String attachmentUrls, boolean async) throws StateException { ... public static void sendDocMail(final String from, final String to, final String cc, final String key, final long docId, boolean async) throws StateException { ... private static void send(Runnable task, boolean async) { if (async) { AsyncExecutor.submit(task); } else { task.run(); } }
public class MailSender { static void sendMailAndRecordHistory(String from, String to, String cc, String key, String params, String attachmentUrls, long docId) throws StateException { ... String embedImgBody = MailUtil.embedImg(body, email); public class MailUtil { static final Pattern HTML_URL = Pattern.compile("<img src=(?:\"|')(.+)(?:\"|')", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public static String embedImg(String body, final HtmlEmail email) throws EmailException { return StringUtil.resolveReplacement(body, HTML_URL, new Presentable<Matcher>() { @Override public String toString(Matcher matcher) { String url = matcher.group(1); cid = email.embed(url, UUID.nameUUIDFromBytes(url.getBytes()).toString()); } return "<img src=\"cid:" + cid + "\""; ...
<%@page pageEncoding="UTF-8" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Error Report</title> </head> <body> <h2>Error Report from '${user}'</h2> <b>Message:</b> <pre> ${message} </pre> <b>Screenshot:</b><br> <img src="${screenshot}"> </body> </html>
public class MailUtil { static Pattern DATA_PROTOCOL = Pattern.compile("^data:(.+);(.+),"); public static String embedImg(String body, final HtmlEmail email) throws EmailException { return StringUtil.resolveReplacement(body, HTML_URL, new Presentable<Matcher>() { @Override public String toString(Matcher matcher) { String url = matcher.group(1); String cid; try { Matcher m = DATA_PROTOCOL.matcher(url); if (m.find()) { final String cType = m.group(1); final String encoding = m.group(2); final String content = url.substring(m.toMatchResult().end()); cid = email.embed(new javax.activation.DataSource() { @Override public InputStream getInputStream() throws IOException { try { return javax.mail.internet.MimeUtility.decode(new ByteArrayInputStream(IOUtil.getBytes(content)), encoding); } catch (MessagingException e) { throw LOGGER.getIllegalStateException("Image encoding failed", e); } } // empty realization for other javax.activation.DataSource methods ... }, UUID.randomUUID().toString()); } else { cid = email.embed(url, UUID.nameUUIDFromBytes(url.getBytes()).toString()); } return "<img src=\"cid:" + cid + "\""; ...
Source: https://habr.com/ru/post/166727/
All Articles