List of usage examples for org.apache.commons.mail Email addTo
public Email addTo(final String... emails) throws EmailException
From source file:org.jwebsocket.plugins.mail.MailPlugInService.java
/** * * @param aToken/*from www . j a va 2 s. com*/ * @return */ public Token sendMail(Token aToken) { String lFrom = aToken.getString("from", "[unknown]"); String lTo = aToken.getString("to"); String lCC = aToken.getString("cc"); String lBCC = aToken.getString("bcc"); String lSubject = aToken.getString("subject"); String lBody = aToken.getString("body"); Boolean lIsHTML = aToken.getBoolean("html", false); List<Object> lAttachedFiles = aToken.getList("attachments"); String lMsg; // instantiate response token Token lResponse = TokenFactory.createToken(); Map<String, String> lMap = new FastMap<String, String>(); if (lFrom != null && lFrom.length() > 0) { lMap.put("from", lFrom); } if (lTo != null && lTo.length() > 0) { lMap.put("to", lTo); } if (lCC != null && lCC.length() > 0) { lMap.put("cc", lCC); } if (lBCC != null && lBCC.length() > 0) { lMap.put("bcc", lBCC); } if (lSubject != null && lSubject.length() > 0) { lMap.put("subject", lSubject); } if (lBody != null && lBody.length() > 0) { lMap.put("body", lBody); } // Create the attachment List<EmailAttachment> lEmailAttachments = new FastList<EmailAttachment>(); if (lAttachedFiles != null) { for (Object lAttachedFile : lAttachedFiles) { EmailAttachment lAttachment = new EmailAttachment(); lAttachment.setPath((String) lAttachedFile); lAttachment.setDisposition(EmailAttachment.ATTACHMENT); // lAttachment.setDescription( "Picture of John" ); // lAttachment.setName( "John" ); lEmailAttachments.add(lAttachment); } } // Create the lEmail message if (mLog.isDebugEnabled()) { mLog.debug("Sending e-mail to " + lTo + " with subject '" + lSubject + "'..."); } try { Email lEmail; if (lIsHTML) { lEmail = new HtmlEmail(); } else { lEmail = new MultiPartEmail(); } lEmail.setHostName(mSettings.getSmtpHost()); lEmail.setSmtpPort(mSettings.getSmtpPort()); if (mSettings.getSmtpAuth()) { lEmail.setAuthentication(mSettings.getSmtpUser(), mSettings.getSmtpPassword()); } if (mSettings.getSmtpPop3Before()) { lEmail.setPopBeforeSmtp(true, mSettings.getPop3Host(), mSettings.getPop3User(), mSettings.getPop3Password()); } if (lFrom != null && lFrom.length() > 0) { lEmail.setFrom(lFrom); } if (lTo != null && lTo.length() > 0) { String[] lToSplit = lTo.split(";"); for (String lToSplit1 : lToSplit) { if (lToSplit1 != null && lToSplit1.length() > 0) { lEmail.addTo(lToSplit1.trim()); } } } if (lCC != null && lCC.length() > 0) { String[] lCCSplit = lCC.split(";"); for (String lCCSplit1 : lCCSplit) { if (lCCSplit1 != null && lCCSplit1.length() > 0) { lEmail.addCc(lCCSplit1.trim()); } } } if (lBCC != null && lBCC.length() > 0) { String[] lBCCSplit = lBCC.split(";"); for (String lBCCSplit1 : lBCCSplit) { if (lBCCSplit1 != null && lBCCSplit1.length() > 0) { lEmail.addBcc(lBCCSplit1.trim()); } } } if (lSubject != null && lSubject.length() > 0) { lEmail.setSubject(lSubject); } if (lBody != null && lBody.length() > 0) { if (lIsHTML) { HtmlEmail lHTML = ((HtmlEmail) lEmail); /* * URL lURL = new * URL("http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg"); * String lCID = ((HtmlEmail )lEmail).embed(lURL, "five feet * further logo"); * * //url = new URL( * "http://five-feet-further.com/resources/css/IJX4FWDocu.css" * ); // String css = ((HtmlEmail)lEmail).embed( url, "name * of css" ); * * ((HtmlEmail )lEmail).setHtmlMsg( "<html><body>" + "<style * type=\"text/css\">" + "h1 { " + " font-family:arial, * helvetica, sans-serif;" + " font-weight:bold;" + " * font-size:18pt;" + "}" + "</style>" + // "<link * href=\"cid:" + css + "\" type=\"text/css\" * rel=\"stylesheet\">" + "<p><img src=\"cid:" + lCID + * "\"></p>" + "<p><img * src=\"http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg\"></p>" * + lItem + "</body></html>"); */ /* * // Now the message body. Multipart mp = new * MimeMultipart(); * * BodyPart textPart = new MimeBodyPart(); // sets type to * "text/plain" textPart.setText("Kann Ihr Browser keine * HTML-Mails darstellen?"); * * BodyPart pixPart = new MimeBodyPart(); * pixPart.setContent(lMsg, "text/html"); * * // Collect the Parts into the MultiPart * mp.addBodyPart(textPart); mp.addBodyPart(pixPart); * * // Put the MultiPart into the Message ((HtmlEmail) * lEmail).setContent((MimeMultipart)mp); ((HtmlEmail) * lEmail).buildMimeMessage(); * * /* * // ((HtmlEmail) lEmail).setContent(lMsg, * Email.TEXT_HTML); * * // lHeaders.put("Innotrade-Id", "4711-0815"); // * lHTML.setHeaders(lHeaders); // ((HtmlEmail) * lEmail).setCharset("UTF-8"); // ((HtmlEmail) * lEmail).setMsg(lMsg); lMM.setHeader("Innotrade-Id", * "4711-0815"); * * // ((HtmlEmail) lEmail).setContent(lTxtMsg, * Email.TEXT_PLAIN); */ // String lTxtMsg = "Your Email-Client does not support HTML messages."; lHTML.setHtmlMsg(lBody); // lHTML.setTextMsg(lTxtMsg); } else { lEmail.setMsg(lBody); } } // add attachment(s), if such for (EmailAttachment lAttachment : lEmailAttachments) { ((MultiPartEmail) lEmail).attach(lAttachment); } // send the Email String lMsgId = lEmail.send(); if (mLog.isInfoEnabled()) { lMsg = "Email successfully sent" + " from " + (lFrom != null ? lFrom : "(no sender)") + " to " + (lTo != null ? lTo : "(no recipient)") + " cc " + (lCC != null ? lCC : "(no recipient)") + ", subject " + (lSubject != null ? "'" + lSubject + "'" : "(no subject)") + ", msgId " + lMsgId; mLog.info(lMsg); } lResponse.setInteger("code", 0); lResponse.setString("msg", "ok"); lResponse.setString("msgId", lMsgId); } catch (EmailException lEx) { lMsg = lEx.getClass().getSimpleName() + " (" + lEx.getCause().getClass().getSimpleName() + "): " + lEx.getMessage(); mLog.error(lMsg); lResponse.setInteger("code", -1); lResponse.setString("msg", lMsg); } return lResponse; }
From source file:org.killbill.billing.plugin.notification.email.EmailSender.java
private void sendEmail(final List<String> to, final List<String> cc, final String subject, final Email email) throws EmailException { if (logOnly) { return;/*from w w w.j av a 2s . c o m*/ } email.setSmtpPort(useSmtpPort); if (useSmtpAuth) { email.setAuthentication(smtpUserName, smtpUserPassword); } email.setHostName(smtpServerName); email.setFrom(from); email.setSubject(subject); if (to != null) { for (final String recipient : to) { email.addTo(recipient); } } if (cc != null) { for (final String recipient : cc) { email.addCc(recipient); } } email.setSSL(useSSL); logService.log(LogService.LOG_INFO, String.format("Sending email to %s, cc %s, subject %s", to, cc, subject)); email.send(); }
From source file:org.killbill.billing.util.email.DefaultEmailSender.java
private void sendEmail(final List<String> to, final List<String> cc, final String subject, final Email email) throws EmailApiException { try {//from www . ja v a 2s . com email.setSmtpPort(config.getSmtpPort()); if (config.useSmtpAuth()) { email.setAuthentication(config.getSmtpUserName(), config.getSmtpPassword()); } email.setHostName(config.getSmtpServerName()); email.setFrom(config.getDefaultFrom()); email.setSubject(subject); if (to != null) { for (final String recipient : to) { email.addTo(recipient); } } if (cc != null) { for (final String recipient : cc) { email.addCc(recipient); } } email.setSSL(config.useSSL()); log.info("Sending email to='{}', cc='{}', subject='{}'", to, cc, subject); email.send(); } catch (EmailException ee) { throw new EmailApiException(ee, ErrorCode.EMAIL_SENDING_FAILED); } }
From source file:org.kuali.mobility.email.service.EmailServiceImpl.java
@Override public boolean sendEmail(String body, String subject, String emailAddressTo, String emailAddressFrom) { boolean emailSent = false; if (emailAddressFrom == null || StringUtils.isEmpty(emailAddressFrom)) { emailAddressFrom = kmeProperties.getProperty("email.from"); if (emailAddressFrom == null) { return emailSent; }/* ww w. j ava 2 s. co m*/ } if (emailAddressTo == null || StringUtils.isEmpty(emailAddressTo)) { return emailSent; } if (subject == null || StringUtils.isEmpty(subject)) { return emailSent; } if (body == null || StringUtils.isEmpty(body)) { return emailSent; } try { Email email = new SimpleEmail(); email.setHostName(kmeProperties.getProperty("email.host")); email.setSmtpPort(Integer.parseInt(kmeProperties.getProperty("email.port"))); email.setAuthenticator(new DefaultAuthenticator(kmeProperties.getProperty("email.username"), kmeProperties.getProperty("email.passsword"))); email.setSSLOnConnect(true); email.setFrom(emailAddressFrom); email.setSubject(subject); email.setMsg(body); email.addTo(emailAddressTo); email.send(); emailSent = true; LOG.debug("Mail Sent..."); } catch (EmailException e) { LOG.error("Mail send failed...", e); } return emailSent; }
From source file:org.mifosplatform.infrastructure.security.service.JpaPlatformUserLoginFailureService.java
private void notify(String username, Integer failures) { GlobalConfigurationProperty property = globalConfigurationRepository.findOneByName("login-failure-limit"); Long limit = 3l;//from w ww .j a v a2 s.com if (property != null && property.isEnabled() && property.getValue() != null) { limit = property.getValue(); } // NOTE: only send the email once if (failures == limit.intValue()) { lock(username); try { StringBuilder message = new StringBuilder(); message.append(String.format(template, limit)); final Email email = new SimpleEmail(); EmailCredentialsData credentials = getCredentials(); email.setAuthenticator( new DefaultAuthenticator(credentials.getAuthUsername(), credentials.getAuthPassword())); email.setDebug(credentials.isDebug()); email.setHostName(credentials.getHost()); email.setSmtpPort(credentials.getSmtpPort()); email.setStartTLSRequired(true); email.setStartTLSEnabled(credentials.isStartTls()); email.getMailSession().getProperties().put("mail.smtp.auth", true); email.setFrom(credentials.getAuthUsername(), credentials.getSenderName()); email.setSubject(subject); email.setMsg(message.toString()); email.addTo(appUserRepository.getEmailByUsername(username)); email.send(); } catch (Exception e) { logger.warn(e.toString(), e); } throw new LockedException( "User " + username + " has been locked after " + limit + " failed login attempts."); } }
From source file:org.ms123.common.workflow.tasks.TaskMailExecutor.java
protected void addTo(Email email, String to) { String[] tos = splitAndTrim(to); if (tos != null) { for (String t : tos) { try { email.addTo(t); } catch (EmailException e) { throw new RuntimeException("TaskMailExecutor:Could not add " + t + " as recipient", e); }//from w w w .ja v a 2 s . c o m } } else { throw new RuntimeException("TaskMailExecutor:No recipient could be found for sending email"); } }
From source file:org.ms123.common.workflow.TaskSendExecutor.java
protected void addTo(Email email, String to) { String[] tos = splitAndTrim(to); if (tos != null) { for (String t : tos) { try { email.addTo(t); } catch (EmailException e) { throw new RuntimeException("TaskSendExecutor:Could not add " + t + " as recipient", e); }//from ww w .j a v a 2 s . co m } } else { throw new RuntimeException("TaskSendExecutor:No recipient could be found for sending email"); } }
From source file:org.opencms.newsletter.CmsNewsletter.java
/** * Returns the e-mail for the newsletter.<p> * //from ww w. j a va 2 s .com * @param recipient the recipient to whom the newsletter is sent * @param cms the CmsObject * * @return the e-mail for the newsletter * * @throws CmsException if something goes wrong */ public Email getEmail(CmsObject cms, I_CmsNewsletterRecipient recipient) throws CmsException { StringBuffer htmlMsg = new StringBuffer(1024); StringBuffer txtMsg = new StringBuffer(1024); Iterator contents = m_contents.iterator(); while (contents.hasNext()) { I_CmsNewsletterContent content = (I_CmsNewsletterContent) contents.next(); if (recipient.isSubscriber(content)) { if (content.getType().equals(CmsNewsletterContentType.TYPE_HTML)) { htmlMsg.append(content.getContent()); } else { txtMsg.append(content.getContent()); } } } Email email = null; try { if ((htmlMsg.length() > 0) || !m_attachments.isEmpty()) { // we need to create a HTML mail CmsHtmlMail htmlMail = new CmsHtmlMail(); htmlMail.setHtmlMsg(replaceMacros(htmlMsg.toString(), recipient)); Iterator attachments = m_attachments.iterator(); while (attachments.hasNext()) { CmsResource resource = (CmsResource) attachments.next(); // set the description of the attachment either to the // property description, if it is set, or // to the property title String description = ""; String propertyDescription = cms.readPropertyObject(cms.getSitePath(resource), CmsPropertyDefinition.PROPERTY_DESCRIPTION, true).getValue(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(propertyDescription)) { description = propertyDescription; } else { String propertyTitle = cms.readPropertyObject(cms.getSitePath(resource), CmsPropertyDefinition.PROPERTY_TITLE, true).getValue(); description = propertyTitle; } htmlMail.attach(new CmsVfsDataSource(cms, resource), resource.getName(), description); } htmlMail.setTextMsg(replaceMacros(txtMsg.toString(), recipient)); email = htmlMail; } else { // only text content, return text mail CmsSimpleMail textMail = new CmsSimpleMail(); textMail.setMsg(replaceMacros(txtMsg.toString(), recipient)); email = textMail; } email.addTo(recipient.getEmail()); email.setSubject(m_subject); } catch (EmailException e) { LOG.error(Messages.get().getBundle().key(Messages.LOG_COMPOSE_MAIL_ERR_0), e); } return email; }
From source file:org.openepics.discs.calib.ejb.ReminderSvc.java
private void sendMail(String from, String[] to, String subject, String message) { try {//from w ww . j av a 2 s.c o m Email email = new SimpleEmail(); logger.info("sending email ..."); email.setHostName("exchange.nscl.msu.edu"); email.setSmtpPort(25); // email.setSmtpPort(465); // email.setAuthenticator(new DefaultAuthenticator("iser", "xxxxxx")); // email.setSSLOnConnect(true); email.setTLS(true); // email.setDebug(true); email.setFrom(from); email.setSubject(subject); email.setMsg(message); email.addTo(to); email.send(); } catch (Exception e) { logger.severe("error while sending email"); } }
From source file:org.openhab.action.mail.internal.Mail.java
/** * Sends an email with attachment(s) via SMTP * //from w ww . j a v a2s . c o m * @param to the email address of the recipient * @param subject the subject of the email * @param message the body of the email * @param attachmentUrlList a list of URL strings of the contents to send as attachments * * @return <code>true</code>, if sending the email has been successful and * <code>false</code> in all other cases. */ @ActionDoc(text = "Sends an email with attachment via SMTP") static public boolean sendMail(@ParamDoc(name = "to") String to, @ParamDoc(name = "subject") String subject, @ParamDoc(name = "message") String message, @ParamDoc(name = "attachmentUrlList") List<String> attachmentUrlList) { boolean success = false; if (MailActionService.isProperlyConfigured) { Email email = new SimpleEmail(); if (attachmentUrlList != null && !attachmentUrlList.isEmpty()) { email = new MultiPartEmail(); for (String attachmentUrl : attachmentUrlList) { // Create the attachment try { EmailAttachment attachment = new EmailAttachment(); attachment.setURL(new URL(attachmentUrl)); attachment.setDisposition(EmailAttachment.ATTACHMENT); String fileName = attachmentUrl.replaceFirst(".*/([^/?]+).*", "$1"); attachment.setName(StringUtils.isNotBlank(fileName) ? fileName : "Attachment"); ((MultiPartEmail) email).attach(attachment); } catch (MalformedURLException e) { logger.error("Invalid attachment url.", e); } catch (EmailException e) { logger.error("Error adding attachment to email.", e); } } } email.setHostName(hostname); email.setSmtpPort(port); email.setTLS(tls); if (StringUtils.isNotBlank(username)) { if (popBeforeSmtp) { email.setPopBeforeSmtp(true, hostname, username, password); } else { email.setAuthenticator(new DefaultAuthenticator(username, password)); } } try { if (StringUtils.isNotBlank(charset)) { email.setCharset(charset); } email.setFrom(from); String[] toList = to.split(";"); for (String toAddress : toList) { email.addTo(toAddress); } if (!StringUtils.isEmpty(subject)) email.setSubject(subject); if (!StringUtils.isEmpty(message)) email.setMsg(message); email.send(); logger.debug("Sent email to '{}' with subject '{}'.", to, subject); success = true; } catch (EmailException e) { logger.error("Could not send e-mail to '" + to + "'.", e); } } else { logger.error( "Cannot send e-mail because of missing configuration settings. The current settings are: " + "Host: '{}', port '{}', from '{}', useTLS: {}, username: '{}', password '{}'", new Object[] { hostname, String.valueOf(port), from, String.valueOf(tls), username, password }); } return success; }