List of usage examples for org.apache.commons.mail Email setCharset
public void setCharset(final String newCharset)
From source file:net.scran24.user.server.services.HelpServiceImpl.java
@Override public void reportUncaughtException(String strongName, List<String> classNames, List<String> messages, List<StackTraceElement[]> stackTraces, String surveyState) { Subject subject = SecurityUtils.getSubject(); ScranUserId userId = (ScranUserId) subject.getPrincipal(); if (userId == null) throw new RuntimeException("User must be logged in"); String rateKey = userId.survey + "#" + userId.username; RateInfo rateInfo = rateMap.get(rateKey); boolean rateExceeded = false; long time = System.currentTimeMillis(); if (rateInfo == null) { rateMap.put(rateKey, new RateInfo(1, time)); } else {// w w w. j av a 2s . c o m long timeSinceLastRequest = time - rateInfo.lastRequestTime; if (timeSinceLastRequest > 10000) { rateMap.put(rateKey, new RateInfo(1, time)); } else if (rateInfo.requestCount >= 10) { rateExceeded = true; } else { rateMap.put(rateKey, new RateInfo(rateInfo.requestCount + 1, time)); } } if (!rateExceeded) { System.out.println(String.format("Sending email", userId.survey, userId.username)); Email email = new SimpleEmail(); email.setHostName(smtpHostName); email.setSmtpPort(smtpPort); email.setCharset(EmailConstants.UTF_8); email.setAuthenticator(new DefaultAuthenticator(smtpUserName, smtpPassword)); email.setSSLOnConnect(true); StringBuilder sb = new StringBuilder(); for (int i = 0; i < classNames.size(); i++) { sb.append(String.format("%s: %s\n", classNames.get(i), messages.get(i))); StackTraceElement[] deobfStackTrace = deobfuscator.resymbolize(stackTraces.get(i), strongName); for (StackTraceElement ste : deobfStackTrace) { sb.append(String.format(" %s\n", ste.toString())); } sb.append("\n"); } sb.append("Survey state:\n"); sb.append(surveyState); sb.append("\n"); try { email.setFrom("no-reply@intake24.co.uk", "Intake24"); email.setSubject(String.format("Client exception (%s/%s): %s", userId.survey, userId.username, messages.get(0))); email.setMsg(sb.toString()); email.addTo("bugs@intake24.co.uk"); email.send(); } catch (EmailException ee) { log.error("Failed to send e-mail notification", ee); } } }
From source file:com.mirth.connect.connectors.smtp.SmtpMessageDispatcher.java
@Override public void doDispatch(UMOEvent event) throws Exception { monitoringController.updateStatus(connector, connectorType, Event.BUSY); MessageObject mo = messageObjectController.getMessageObjectFromEvent(event); if (mo == null) { return;//from w w w .ja va 2s. co m } try { Email email = null; if (connector.isHtml()) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(connector.getCharsetEncoding()); email.setHostName(replacer.replaceValues(connector.getSmtpHost(), mo)); try { email.setSmtpPort(Integer.parseInt(replacer.replaceValues(connector.getSmtpPort(), mo))); } catch (NumberFormatException e) { // Don't set if the value is invalid } try { email.setSocketConnectionTimeout( Integer.parseInt(replacer.replaceValues(connector.getTimeout(), mo))); } catch (NumberFormatException e) { // Don't set if the value is invalid } if ("SSL".equalsIgnoreCase(connector.getEncryption())) { email.setSSL(true); } else if ("TLS".equalsIgnoreCase(connector.getEncryption())) { email.setTLS(true); } if (connector.isAuthentication()) { email.setAuthentication(replacer.replaceValues(connector.getUsername(), mo), replacer.replaceValues(connector.getPassword(), mo)); } /* * NOTE: There seems to be a bug when calling setTo with a List * (throws a java.lang.ArrayStoreException), so we are using addTo * instead. */ for (String to : replaceValuesAndSplit(connector.getTo(), mo)) { email.addTo(to); } // Currently unused for (String cc : replaceValuesAndSplit(connector.cc(), mo)) { email.addCc(cc); } // Currently unused for (String bcc : replaceValuesAndSplit(connector.getBcc(), mo)) { email.addBcc(bcc); } // Currently unused for (String replyTo : replaceValuesAndSplit(connector.getReplyTo(), mo)) { email.addReplyTo(replyTo); } for (Entry<String, String> header : connector.getHeaders().entrySet()) { email.addHeader(replacer.replaceValues(header.getKey(), mo), replacer.replaceValues(header.getValue(), mo)); } email.setFrom(replacer.replaceValues(connector.getFrom(), mo)); email.setSubject(replacer.replaceValues(connector.getSubject(), mo)); String body = replacer.replaceValues(connector.getBody(), mo); if (connector.isHtml()) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } /* * If the MIME type for the attachment is missing, we display a * warning and set the content anyway. If the MIME type is of type * "text" or "application/xml", then we add the content. If it is * anything else, we assume it should be Base64 decoded first. */ for (Attachment attachment : connector.getAttachments()) { String name = replacer.replaceValues(attachment.getName(), mo); String mimeType = replacer.replaceValues(attachment.getMimeType(), mo); String content = replacer.replaceValues(attachment.getContent(), mo); byte[] bytes; if (StringUtils.indexOf(mimeType, "/") < 0) { logger.warn("valid MIME type is missing for email attachment: \"" + name + "\", using default of text/plain"); attachment.setMimeType("text/plain"); bytes = content.getBytes(); } else if ("application/xml".equalsIgnoreCase(mimeType) || StringUtils.startsWith(mimeType, "text/")) { logger.debug("text or XML MIME type detected for attachment \"" + name + "\""); bytes = content.getBytes(); } else { logger.debug("binary MIME type detected for attachment \"" + name + "\", performing Base64 decoding"); bytes = Base64.decodeBase64(content); } ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null); } /* * From the Commons Email JavaDoc: send returns * "the message id of the underlying MimeMessage". */ String response = email.send(); messageObjectController.setSuccess(mo, response, null); } catch (EmailException e) { alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_402, "Error sending email message.", e); messageObjectController.setError(mo, Constants.ERROR_402, "Error sending email message.", e, null); connector.handleException(new Exception(e)); } finally { monitoringController.updateStatus(connector, connectorType, Event.DONE); } }
From source file:com.kylinolap.common.util.MailService.java
/** * /*w ww . j a va 2 s .co m*/ * @param receivers * @param subject * @param content * @return true or false indicating whether the email was delivered successfully * @throws IOException */ public boolean sendMail(List<String> receivers, String subject, String content) throws IOException { if (!enabled) { logger.info("Email service is disabled; this mail will not be delivered: " + subject); logger.info("To enable mail service, set 'mail.enabled=true' in kylin.properties"); return false; } Email email = new HtmlEmail(); email.setHostName(host); if (username != null && username.trim().length() > 0) { email.setAuthentication(username, password); } //email.setDebug(true); try { for (String receiver : receivers) { email.addTo(receiver); } email.setFrom(sender); email.setSubject(subject); email.setCharset("UTF-8"); ((HtmlEmail) email).setHtmlMsg(content); email.send(); email.getMailSession(); } catch (EmailException e) { logger.error(e.getLocalizedMessage(), e); return false; } return true; }
From source file:net.scran24.user.server.services.HelpServiceImpl.java
private void sendEmailNotification(String name, String surveyId, String number, List<String> addresses) { Email email = new SimpleEmail(); email.setHostName(smtpHostName);//from w ww .ja v a 2 s. co m email.setSmtpPort(smtpPort); email.setAuthenticator(new DefaultAuthenticator(smtpUserName, smtpPassword)); email.setSSLOnConnect(true); email.setCharset(EmailConstants.UTF_8); try { email.setFrom(fromEmail, fromName); email.setSubject("Someone needs help completing their survey"); email.setMsg("Please call " + name + " on " + number + " (survey id: " + surveyId + ")"); for (String address : addresses) email.addTo(address); email.send(); } catch (EmailException e) { log.error("Failed to send e-mail notification", e); } }
From source file:com.mirth.connect.connectors.smtp.SmtpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) { SmtpDispatcherProperties smtpDispatcherProperties = (SmtpDispatcherProperties) connectorProperties; String responseData = null;/*from ww w. j av a2 s .c o m*/ String responseError = null; String responseStatusMessage = null; Status responseStatus = Status.QUEUED; String info = "From: " + smtpDispatcherProperties.getFrom() + " To: " + smtpDispatcherProperties.getTo() + " SMTP Info: " + smtpDispatcherProperties.getSmtpHost() + ":" + smtpDispatcherProperties.getSmtpPort(); eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WRITING, info)); try { Email email = null; if (smtpDispatcherProperties.isHtml()) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charsetEncoding); email.setHostName(smtpDispatcherProperties.getSmtpHost()); try { email.setSmtpPort(Integer.parseInt(smtpDispatcherProperties.getSmtpPort())); } catch (NumberFormatException e) { // Don't set if the value is invalid } try { int timeout = Integer.parseInt(smtpDispatcherProperties.getTimeout()); email.setSocketTimeout(timeout); email.setSocketConnectionTimeout(timeout); } catch (NumberFormatException e) { // Don't set if the value is invalid } // This has to be set before the authenticator because a session shouldn't be created yet configuration.configureEncryption(connectorProperties, email); if (smtpDispatcherProperties.isAuthentication()) { email.setAuthentication(smtpDispatcherProperties.getUsername(), smtpDispatcherProperties.getPassword()); } Properties mailProperties = email.getMailSession().getProperties(); // These have to be set after the authenticator, so that a new mail session isn't created configuration.configureMailProperties(mailProperties); if (smtpDispatcherProperties.isOverrideLocalBinding()) { mailProperties.setProperty("mail.smtp.localaddress", smtpDispatcherProperties.getLocalAddress()); mailProperties.setProperty("mail.smtp.localport", smtpDispatcherProperties.getLocalPort()); } /* * NOTE: There seems to be a bug when calling setTo with a List (throws a * java.lang.ArrayStoreException), so we are using addTo instead. */ for (String to : StringUtils.split(smtpDispatcherProperties.getTo(), ",")) { email.addTo(to); } // Currently unused for (String cc : StringUtils.split(smtpDispatcherProperties.getCc(), ",")) { email.addCc(cc); } // Currently unused for (String bcc : StringUtils.split(smtpDispatcherProperties.getBcc(), ",")) { email.addBcc(bcc); } // Currently unused for (String replyTo : StringUtils.split(smtpDispatcherProperties.getReplyTo(), ",")) { email.addReplyTo(replyTo); } for (Entry<String, String> header : smtpDispatcherProperties.getHeaders().entrySet()) { email.addHeader(header.getKey(), header.getValue()); } email.setFrom(smtpDispatcherProperties.getFrom()); email.setSubject(smtpDispatcherProperties.getSubject()); AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider(); String body = attachmentHandlerProvider.reAttachMessage(smtpDispatcherProperties.getBody(), connectorMessage); if (StringUtils.isNotEmpty(body)) { if (smtpDispatcherProperties.isHtml()) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } } /* * If the MIME type for the attachment is missing, we display a warning and set the * content anyway. If the MIME type is of type "text" or "application/xml", then we add * the content. If it is anything else, we assume it should be Base64 decoded first. */ for (Attachment attachment : smtpDispatcherProperties.getAttachments()) { String name = attachment.getName(); String mimeType = attachment.getMimeType(); String content = attachment.getContent(); byte[] bytes; if (StringUtils.indexOf(mimeType, "/") < 0) { logger.warn("valid MIME type is missing for email attachment: \"" + name + "\", using default of text/plain"); attachment.setMimeType("text/plain"); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding, false); } else if ("application/xml".equalsIgnoreCase(mimeType) || StringUtils.startsWith(mimeType, "text/")) { logger.debug("text or XML MIME type detected for attachment \"" + name + "\""); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding, false); } else { logger.debug("binary MIME type detected for attachment \"" + name + "\", performing Base64 decoding"); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, null, true); } ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null); } /* * From the Commons Email JavaDoc: send returns * "the message id of the underlying MimeMessage". */ responseData = email.send(); responseStatus = Status.SENT; responseStatusMessage = "Email sent successfully."; } catch (Exception e) { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error sending email message", e)); responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error sending email message", e); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), "Error sending email message", e); // TODO: Exception handling // connector.handleException(new Exception(e)); } finally { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE)); } return new Response(responseStatus, responseData, responseStatusMessage, responseError); }
From source file:com.music.service.EmailService.java
private Email createEmail(boolean html) { Email e = null; if (html) {//ww w . j av a2 s .c o m e = new HtmlEmail(); } else { e = new SimpleEmail(); } e.setHostName(smtpHost); if (!StringUtils.isEmpty(smtpUser)) { e.setAuthentication(smtpUser, smtpPassword); } if (!StringUtils.isEmpty(smtpBounceEmail)) { e.setBounceAddress(smtpBounceEmail); } e.setTLS(true); e.setSmtpPort(587); //tls port e.setCharset("UTF8"); //e.setDebug(true); return e; }
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!//from w w w. j a v a 2s .c om * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param ideIdint DOCUMENT ME! * @param to DOCUMENT ME! * @param cc DOCUMENT ME! * @param bcc DOCUMENT ME! * @param subject DOCUMENT ME! * @param body DOCUMENT ME! * @param attachments DOCUMENT ME! * @param isHtml DOCUMENT ME! * @param charset DOCUMENT ME! * @param headers DOCUMENT ME! * @param priority DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeDraftMessage(getId(), mime, user); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!//from www .ja v a 2s . c om * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param identity DOCUMENT ME! * @param to DOCUMENT ME! * @param cc DOCUMENT ME! * @param bcc DOCUMENT ME! * @param subject DOCUMENT ME! * @param body DOCUMENT ME! * @param attachments DOCUMENT ME! * @param isHtml DOCUMENT ME! * @param charset DOCUMENT ME! * @param headers DOCUMENT ME! * @param priority DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void send(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } String mid = getId(); if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } else { email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.saveSentMessage(mid, mime, user); Thread thread = new Thread(new SendMessageThread(email)); thread.start(); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:de.cosmocode.palava.services.mail.EmailFactory.java
@SuppressWarnings("unchecked") Email build(Document document, Embedder embed) throws EmailException, FileNotFoundException { /* CHECKSTYLE:ON */ final Element root = document.getRootElement(); final List<Element> messages = root.getChildren("message"); if (messages.isEmpty()) throw new IllegalArgumentException("No messages found"); final List<Element> attachments = root.getChildren("attachment"); final Map<ContentType, String> available = new HashMap<ContentType, String>(); for (Element element : messages) { final String type = element.getAttributeValue("type"); final ContentType messageType = StringUtils.equals(type, "html") ? ContentType.HTML : ContentType.PLAIN; if (available.containsKey(messageType)) { throw new IllegalArgumentException("Two messages with the same types have been defined."); }//from www .ja v a 2 s . c o m available.put(messageType, element.getText()); } final Email email; if (available.containsKey(ContentType.HTML) || attachments.size() > 0) { final HtmlEmail htmlEmail = new HtmlEmail(); htmlEmail.setCharset(CHARSET); if (embed.hasEmbeddings()) { htmlEmail.setSubType("related"); } else if (attachments.size() > 0) { htmlEmail.setSubType("related"); } else { htmlEmail.setSubType("alternative"); } /** * Add html message */ if (available.containsKey(ContentType.HTML)) { htmlEmail.setHtmlMsg(available.get(ContentType.HTML)); } /** * Add plain text alternative */ if (available.containsKey(ContentType.PLAIN)) { htmlEmail.setTextMsg(available.get(ContentType.PLAIN)); } /** * Embedded binary data */ for (Map.Entry<String, String> entry : embed.getEmbeddings().entrySet()) { final String path = entry.getKey(); final String cid = entry.getValue(); final String name = embed.name(path); final File file; if (path.startsWith(File.separator)) { file = new File(path); } else { file = new File(embed.getResourcePath(), path); } if (file.exists()) { htmlEmail.embed(new FileDataSource(file), name, cid); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } /** * Attached binary data */ for (Element attachment : attachments) { final String name = attachment.getAttributeValue("name", ""); final String description = attachment.getAttributeValue("description", ""); final String path = attachment.getAttributeValue("path"); if (path == null) throw new IllegalArgumentException("Attachment path was not set"); File file = new File(path); if (!file.exists()) file = new File(embed.getResourcePath(), path); if (file.exists()) { htmlEmail.attach(new FileDataSource(file), name, description); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } email = htmlEmail; } else if (available.containsKey(ContentType.PLAIN)) { email = new SimpleEmail(); email.setCharset(CHARSET); email.setMsg(available.get(ContentType.PLAIN)); } else { throw new IllegalArgumentException("No valid message found in template."); } final String subject = root.getChildText("subject"); email.setSubject(subject); final Element from = root.getChild("from"); final String fromAddress = from == null ? null : from.getText(); final String fromName = from == null ? fromAddress : from.getAttributeValue("name", fromAddress); email.setFrom(fromAddress, fromName); final Element to = root.getChild("to"); if (to != null) { final String toAddress = to.getText(); if (StringUtils.isNotBlank(toAddress) && toAddress.contains(EMAIL_SEPARATOR)) { final String[] toAddresses = toAddress.split(EMAIL_SEPARATOR); for (String address : toAddresses) { email.addTo(address); } } else if (StringUtils.isNotBlank(toAddress)) { final String toName = to.getAttributeValue("name", toAddress); email.addTo(toAddress, toName); } } final Element cc = root.getChild("cc"); if (cc != null) { final String ccAddress = cc.getText(); if (StringUtils.isNotBlank(ccAddress) && ccAddress.contains(EMAIL_SEPARATOR)) { final String[] ccAddresses = ccAddress.split(EMAIL_SEPARATOR); for (String address : ccAddresses) { email.addCc(address); } } else if (StringUtils.isNotBlank(ccAddress)) { final String ccName = cc.getAttributeValue("name", ccAddress); email.addCc(ccAddress, ccName); } } final Element bcc = root.getChild("bcc"); if (bcc != null) { final String bccAddress = bcc.getText(); if (StringUtils.isNotBlank(bccAddress) && bccAddress.contains(EMAIL_SEPARATOR)) { final String[] bccAddresses = bccAddress.split(EMAIL_SEPARATOR); for (String address : bccAddresses) { email.addBcc(address); } } else if (StringUtils.isNotBlank(bccAddress)) { final String bccName = bcc.getAttributeValue("name", bccAddress); email.addBcc(bccAddress, bccName); } } final Element replyTo = root.getChild("replyTo"); if (replyTo != null) { final String replyToAddress = replyTo.getText(); if (StringUtils.isNotBlank(replyToAddress) && replyToAddress.contains(EMAIL_SEPARATOR)) { final String[] replyToAddresses = replyToAddress.split(EMAIL_SEPARATOR); for (String address : replyToAddresses) { email.addReplyTo(address); } } else if (StringUtils.isNotBlank(replyToAddress)) { final String replyToName = replyTo.getAttributeValue("name", replyToAddress); email.addReplyTo(replyToAddress, replyToName); } } return email; }
From source file:org.apache.kylin.common.util.MailService.java
/** * @param receivers/*from w ww . j a va 2 s . com*/ * @param subject * @param content * @return true or false indicating whether the email was delivered successfully * @throws IOException */ public boolean sendMail(List<String> receivers, String subject, String content, boolean isHtmlMsg) { if (!enabled) { logger.info("Email service is disabled; this mail will not be delivered: " + subject); logger.info("To enable mail service, set 'kylin.job.notification-enabled=true' in kylin.properties"); return false; } Email email = new HtmlEmail(); email.setHostName(host); email.setStartTLSEnabled(starttlsEnabled); if (starttlsEnabled) { email.setSslSmtpPort(port); } else { email.setSmtpPort(Integer.valueOf(port)); } if (username != null && username.trim().length() > 0) { email.setAuthentication(username, password); } //email.setDebug(true); try { for (String receiver : receivers) { email.addTo(receiver); } email.setFrom(sender); email.setSubject(subject); email.setCharset("UTF-8"); if (isHtmlMsg) { ((HtmlEmail) email).setHtmlMsg(content); } else { ((HtmlEmail) email).setTextMsg(content); } email.send(); email.getMailSession(); } catch (EmailException e) { logger.error(e.getLocalizedMessage(), e); return false; } return true; }