List of usage examples for org.apache.commons.mail MultiPartEmail MultiPartEmail
MultiPartEmail
From source file:org.openhab.io.net.actions.Mail.java
/** * Sends an email with attachment via SMTP * //from www . java 2 s .com * @param to the email address of the recipient * @param subject the subject of the email * @param message the body of the email * @param attachmentUrl a URL string of the content to send as an attachment * * @return <code>true</code>, if sending the email has been successful and * <code>false</code> in all other cases. */ static public boolean sendMail(String to, String subject, String message, String attachmentUrl) { boolean success = false; if (initialized) { Email email = new SimpleEmail(); if (attachmentUrl != null) { // Create the attachment try { email = new MultiPartEmail(); EmailAttachment attachment = new EmailAttachment(); attachment.setURL(new URL(attachmentUrl)); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setName("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 { email.setFrom(from); email.addTo(to); 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 String[] { hostname, String.valueOf(port), from, String.valueOf(tls), username, password }); } return success; }
From source file:org.paxml.bean.EmailTag.java
private Email createEmail(Collection<String> to, Collection<String> cc, Collection<String> bcc) throws EmailException { Email email;//from www . j a va 2 s . c o m if (attachment == null || attachment.isEmpty()) { email = new SimpleEmail(); } else { MultiPartEmail mpemail = new MultiPartEmail(); for (Object att : attachment) { mpemail.attach(makeAttachment(att.toString())); } email = mpemail; } if (StringUtils.isNotEmpty(username)) { String pwd = null; if (password instanceof Secret) { pwd = ((Secret) password).getDecrypted(); } else if (password != null) { pwd = password.toString(); } email.setAuthenticator(new DefaultAuthenticator(username, pwd)); } email.setHostName(findHost()); email.setSSLOnConnect(ssl); if (port > 0) { if (ssl) { email.setSslSmtpPort(port + ""); } else { email.setSmtpPort(port); } } if (replyTo != null) { for (Object r : replyTo) { email.addReplyTo(r.toString()); } } email.setFrom(from); email.setSubject(subject); email.setMsg(text); if (to != null) { for (String r : to) { email.addTo(r); } } if (cc != null) { for (String r : cc) { email.addCc(r); } } if (bcc != null) { for (String r : bcc) { email.addBcc(r); } } email.setSSLCheckServerIdentity(sslCheckServerIdentity); email.setStartTLSEnabled(tls); email.setStartTLSRequired(tls); return email; }
From source file:org.ploin.pmf.impl.MailSender.java
public SendingResult sendMail(String plain, String html, MailConfig mailConfig, ServerConfig serverConfig, Map<String, String> map) throws MailFactoryException { try {// w w w.j av a2s. c om if (html == null || html.trim().equals("")) { MultiPartEmail email = new MultiPartEmail(); if (mailConfig.isAttachementsEmpty()) { email.setContent(plain, "text/plain; charset=iso-8859-1"); } else { email.setMsg(plain); } return send(email, mailConfig, serverConfig); } HtmlEmail email = new HtmlEmail(); setEmbeds(email, map, html); if (plain != null && !"".equals(plain.trim())) email.setTextMsg(plain); email.setHtmlMsg(html); return send(email, mailConfig, serverConfig); } catch (Exception e) { throw new MailFactoryException(e); } }
From source file:org.sakaiproject.kernel.email.outgoing.OutgoingEmailMessageListener.java
private MultiPartEmail constructMessage(Node messageNode, List<String> recipients) throws EmailException, RepositoryException, PathNotFoundException, ValueFormatException { MultiPartEmail email = new MultiPartEmail(); //TODO: the SAKAI_TO may make no sense in an email context // and there does not appear to be any distinction between Bcc and To in java mail. Set<String> toRecipients = new HashSet<String>(); Set<String> bccRecipients = new HashSet<String>(); for (String r : recipients) { bccRecipients.add(r.trim());//w w w. jav a2 s .co m } if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_TO)) { String[] tor = StringUtils.split(messageNode.getProperty(MessageConstants.PROP_SAKAI_TO).getString(), ','); for (String r : tor) { r = r.trim(); if (bccRecipients.contains(r)) { toRecipients.add(r); bccRecipients.remove(r); } } } for (String r : toRecipients) { email.addTo(r); } for (String r : bccRecipients) { email.addBcc(r); } if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_FROM)) { String from = messageNode.getProperty(MessageConstants.PROP_SAKAI_FROM).getString(); email.setFrom(from); } else { throw new EmailException("Must provide a 'from' address."); } if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_BODY)) { email.setMsg(messageNode.getProperty(MessageConstants.PROP_SAKAI_BODY).getString()); } if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_SUBJECT)) { email.setSubject(messageNode.getProperty(MessageConstants.PROP_SAKAI_SUBJECT).getString()); } if (messageNode.hasNodes()) { NodeIterator ni = messageNode.getNodes(); while (ni.hasNext()) { Node childNode = ni.nextNode(); String description = null; if (childNode.hasProperty(MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION)) { description = childNode.getProperty(MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION) .getString(); } JcrEmailDataSource ds = new JcrEmailDataSource(childNode); email.attach(ds, childNode.getName(), description); } } return email; }
From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java
protected MultiPartEmail constructMessage(Content contentNode, List<String> recipients, javax.jcr.Session session, org.sakaiproject.nakamura.api.lite.Session sparseSession) throws EmailDeliveryException, StorageClientException, AccessDeniedException, PathNotFoundException, RepositoryException, EmailException { MultiPartEmail email = new MultiPartEmail(); Set<String> toRecipients = new HashSet<String>(); toRecipients = setRecipients(recipients, sparseSession); String to = null;// w ww . j ava 2 s. c o m try { // set from: to the reply as address email.setFrom(replyAsAddress, replyAsName); if (toRecipients.size() == 1) { // set to: to the rcpt if sending to just one person to = convertToEmail(toRecipients.iterator().next(), sparseSession); email.setTo(Lists.newArrayList(new InternetAddress(to))); } else { // set to: to 'undisclosed recipients' when sending to a group of recipients // this mirrors what shows up in RFC's and most major MTAs // http://www.postfix.org/postconf.5.html#undisclosed_recipients_header email.addHeader("To", "undisclosed-recipients:;"); } } catch (EmailException e) { LOGGER.error("Cannot send email. From: address as configured is not valid: {}", replyAsAddress); } catch (AddressException e) { LOGGER.error("Cannot send email. To: address is not valid: {}", to); } // if we're dealing with a group of recipients, add them to bcc: to hide email // addresses from the other recipients if (toRecipients.size() > 1) { for (String r : toRecipients) { try { // we don't need to copy the sender on the message if (r.equals(contentNode.getProperty(MessageConstants.PROP_SAKAI_FROM))) { continue; } email.addBcc(convertToEmail(r, sparseSession)); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid To Address [" + r + "], message is being dropped :" + e.getMessage(), e); } } } if (contentNode.hasProperty(MessageConstants.PROP_SAKAI_BODY)) { String messageBody = String.valueOf(contentNode.getProperty(MessageConstants.PROP_SAKAI_BODY)); // if this message has a template, use it LOGGER.debug( "Checking for sakai:templatePath and sakai:templateParams properties on the outgoing message's node."); if (contentNode.hasProperty(MessageConstants.PROP_TEMPLATE_PATH) && contentNode.hasProperty(MessageConstants.PROP_TEMPLATE_PARAMS)) { Map<String, String> parameters = getTemplateProperties( (String) contentNode.getProperty(MessageConstants.PROP_TEMPLATE_PARAMS)); String templatePath = (String) contentNode.getProperty(MessageConstants.PROP_TEMPLATE_PATH); LOGGER.debug("Got the path '{0}' to the template for this outgoing message.", templatePath); Node templateNode = session.getNode(templatePath); if (templateNode.hasProperty("sakai:template")) { String template = templateNode.getProperty("sakai:template").getString(); LOGGER.debug("Pulled the template body from the template node: {0}", template); messageBody = templateService.evaluateTemplate(parameters, template); LOGGER.debug("Performed parameter substitution in the template: {0}", messageBody); } } else { LOGGER.debug( "Message node '{0}' does not have sakai:templatePath and sakai:templateParams properties", contentNode.getPath()); } try { email.setMsg(messageBody); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid Message Body, message is being dropped :" + e.getMessage(), e); } } if (contentNode.hasProperty(MessageConstants.PROP_SAKAI_SUBJECT)) { email.setSubject((String) contentNode.getProperty(MessageConstants.PROP_SAKAI_SUBJECT)); } ContentManager contentManager = sparseSession.getContentManager(); for (String streamId : contentNode.listStreams()) { String description = null; if (contentNode.hasProperty( StorageClientUtils.getAltField(MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION, streamId))) { description = (String) contentNode.getProperty(StorageClientUtils .getAltField(MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION, streamId)); } LiteEmailDataSource ds = new LiteEmailDataSource(contentManager, contentNode, streamId); try { email.attach(ds, streamId, description); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid Attachment [" + streamId + "] message is being dropped :" + e.getMessage(), e); } } return email; }
From source file:org.sakaiproject.nakamura.email.outgoing.OutgoingEmailMessageListener.java
private MultiPartEmail constructMessage(Node messageNode, List<String> recipients) throws EmailDeliveryException, RepositoryException, PathNotFoundException, ValueFormatException { MultiPartEmail email = new MultiPartEmail(); javax.jcr.Session session = messageNode.getSession(); //TODO: the SAKAI_TO may make no sense in an email context // and there does not appear to be any distinction between Bcc and To in java mail. Set<String> toRecipients = new HashSet<String>(); Set<String> bccRecipients = new HashSet<String>(); for (String r : recipients) { bccRecipients.add(convertToEmail(r.trim(), session)); }/*w ww .jav a 2s .co m*/ if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_TO)) { String[] tor = StringUtils.split(messageNode.getProperty(MessageConstants.PROP_SAKAI_TO).getString(), ','); for (String r : tor) { r = convertToEmail(r.trim(), session); if (bccRecipients.contains(r)) { toRecipients.add(r); bccRecipients.remove(r); } } } for (String r : toRecipients) { try { email.addTo(convertToEmail(r, session)); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid To Address [" + r + "], message is being dropped :" + e.getMessage(), e); } } for (String r : bccRecipients) { try { email.addBcc(convertToEmail(r, session)); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid Bcc Address [" + r + "], message is being dropped :" + e.getMessage(), e); } } if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_FROM)) { String from = messageNode.getProperty(MessageConstants.PROP_SAKAI_FROM).getString(); try { email.setFrom(convertToEmail(from, session)); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid From Address [" + from + "], message is being dropped :" + e.getMessage(), e); } } else { throw new EmailDeliveryException("Must provide a 'from' address."); } if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_BODY)) { try { email.setMsg(messageNode.getProperty(MessageConstants.PROP_SAKAI_BODY).getString()); } catch (EmailException e) { throw new EmailDeliveryException( "Invalid Message Body, message is being dropped :" + e.getMessage(), e); } } if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_SUBJECT)) { email.setSubject(messageNode.getProperty(MessageConstants.PROP_SAKAI_SUBJECT).getString()); } if (messageNode.hasNodes()) { NodeIterator ni = messageNode.getNodes(); while (ni.hasNext()) { Node childNode = ni.nextNode(); String description = null; if (childNode.hasProperty(MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION)) { description = childNode.getProperty(MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION) .getString(); } JcrEmailDataSource ds = new JcrEmailDataSource(childNode); try { email.attach(ds, childNode.getName(), description); } catch (EmailException e) { throw new EmailDeliveryException("Invalid Attachment [" + childNode.getName() + "] message is being dropped :" + e.getMessage(), e); } } } return email; }
From source file:org.sigmah.server.schedule.ReportMailerJob.java
private void mailReport(ReportSubscription sub, Date today) throws IOException, SAXException, EmailException { // apply the appropriate filters so the user // only views the reports they're meant to DomainFilters.applyUserFilter(sub.getUser(), em); // load the report definition Report report = null;/* ww w.j a va 2s. c o m*/ try { report = ReportParserJaxb.parseXml(sub.getTemplate().getXml()); } catch (JAXBException e) { e.printStackTrace(); return; } // generate the report reportGenerator.generate(sub.getUser(), report, null, ReportMailerHelper.computeDateRange(report, today)); // render the report to a temporary path and create the // attachement File tempFile = File.createTempFile("report", ".rtf"); FileOutputStream rtf = new FileOutputStream(tempFile); rtfReportRenderer.render(report, rtf); rtf.close(); EmailAttachment attachment = new EmailAttachment(); attachment.setName(report.getContent().getFileName() + reportDateFormat.format(today) + ".rtf"); attachment.setDescription(report.getTitle()); attachment.setPath(tempFile.getAbsolutePath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); // compose both a full html rendering of this report and a short text // message for email clients that can't read html // email MultiPartEmail email = new MultiPartEmail(); // email.setHtmlMsg(ReportMailerHelper.composeHtmlEmail(sub, report )); email.setMsg(ReportMailerHelper.composeTextEmail(sub, report)); email.addTo(sub.getUser().getEmail(), sub.getUser().getName()); email.setSubject("ActivityInfo: " + report.getTitle()); email.attach(attachment); mailer.send(email); }
From source file:org.viafirma.util.SendMailUtil.java
/** * Crea el MIME mensaje aadiendo su contenido, y su destinatario. * @param contentType /* w w w. j av a 2 s . co m*/ * * @throws EmailException */ private MultiPartEmail createMultiPartEmail(String subject, String toUser, String fromAddres, String fromAddresDescription, MimeMultipart aMimeMultipart, String contentType) throws MessagingException, EmailException { MultiPartEmail email = new MultiPartEmail(); email.setContent(aMimeMultipart); email.setHostName(smtpHost); email.addTo(toUser); email.setFrom(fromAddres, fromAddresDescription); email.setSubject(subject); // Si el smtp tiene usuario y pass nos logamos if (StringUtils.isNotEmpty(smtpUser) && StringUtils.isNotEmpty(smtpPass)) { Authenticator auth = new Authenticator() { @Override protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUser, smtpPass); } }; log.info("Para mandar el correo nos autenticamos en el SMTP " + smtpHost + " con user " + smtpUser + " y pass " + CadenaUtilities.getCurrentInstance().generarAsteriscos(smtpPass)); email.setAuthenticator(auth); } // email.setDebug(false); email.buildMimeMessage(); return email; }
From source file:org.wf.dp.dniprorada.util.Mail.java
@Override public void send() throws EmailException { try {//from w w w. j av a 2 s . c o m log.info("init"); MultiPartEmail oMultiPartEmail = new MultiPartEmail(); oMultiPartEmail.setHostName(getHost()); log.info("getHost()=" + getHost()); oMultiPartEmail.addTo(getTo(), "receiver"); log.info("getTo()=" + getTo()); oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov" log.info("getFrom()=" + getFrom()); oMultiPartEmail.setSubject(getHead()); log.info("getHead()=" + getHead()); oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword()); log.info("getAuthUser()=" + getAuthUser()); log.info("getAuthPassword()=" + getAuthPassword()); oMultiPartEmail.setSmtpPort(getPort()); log.info("getPort()=" + getPort()); oMultiPartEmail.setSSL(isSSL()); log.info("isSSL()=" + isSSL()); oMultiPartEmail.setTLS(isTLS()); log.info("isTLS()=" + isTLS()); oSession = oMultiPartEmail.getMailSession(); MimeMessage oMimeMessage = new MimeMessage(oSession); //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING)); oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom())); //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING)); oMimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING)); oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING); _Attach(getBody()); oMimeMessage.setContent(oMultiparts); // oMimeMessage.getRecipients(Message.RecipientType.CC); Transport.send(oMimeMessage); log.info("[send]:Transport.send!"); } catch (Exception exc) { log.error("[send]", exc); throw new EmailException("Error happened when sending email", exc); } }
From source file:org.wf.dp.dniprorada.util.MailOld.java
public void init() throws EmailException { //if(oMultiPartEmail!=null){ // return; //}//w w w .j a v a 2 s. c o m log.info("init"); oMultiPartEmail = new MultiPartEmail(); oMultiPartEmail.setHostName(getHost()); log.info("getHost()=" + getHost()); oMultiPartEmail.addTo(getTo(), "receiver"); log.info("getTo()=" + getTo()); oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov" log.info("getFrom()=" + getFrom()); oMultiPartEmail.setSubject(getHead()); log.info("getHead()=" + getHead()); }