List of usage examples for org.apache.commons.mail MultiPartEmail buildMimeMessage
@Override public void buildMimeMessage() throws EmailException
From source file:com.duroty.application.files.manager.StoreManager.java
/** * DOCUMENT ME!/*from www . j a v a 2 s. 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, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, 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 = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); 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) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); //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.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
From source file:org.apache.nifi.processors.email.ConsumeEWS.java
public MimeMessage parseMessage(EmailMessage item) throws Exception { EmailMessage ewsMessage = item;/*ww w . j ava2 s .c om*/ final String bodyText = ewsMessage.getBody().toString(); MultiPartEmail mm; if (ewsMessage.getBody().getBodyType() == BodyType.HTML) { mm = new HtmlEmail().setHtmlMsg(bodyText); } else { mm = new MultiPartEmail(); mm.setMsg(bodyText); } mm.setHostName("NiFi-EWS"); //from mm.setFrom(ewsMessage.getFrom().getAddress()); //to recipients ewsMessage.getToRecipients().forEach(x -> { try { mm.addTo(x.getAddress()); } catch (EmailException e) { throw new ProcessException("Failed to add TO recipient.", e); } }); //cc recipients ewsMessage.getCcRecipients().forEach(x -> { try { mm.addCc(x.getAddress()); } catch (EmailException e) { throw new ProcessException("Failed to add CC recipient.", e); } }); //subject mm.setSubject(ewsMessage.getSubject()); //sent date mm.setSentDate(ewsMessage.getDateTimeSent()); //add message headers ewsMessage.getInternetMessageHeaders().forEach(x -> mm.addHeader(x.getName(), x.getValue())); //Any attachments if (ewsMessage.getHasAttachments()) { ewsMessage.getAttachments().forEach(x -> { try { FileAttachment file = (FileAttachment) x; file.load(); ByteArrayDataSource bds = new ByteArrayDataSource(file.getContent(), file.getContentType()); mm.attach(bds, file.getName(), "", EmailAttachment.ATTACHMENT); } catch (MessagingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }); } mm.buildMimeMessage(); return mm.getMimeMessage(); }
From source file:org.apache.nifi.processors.email.GenerateAttachment.java
public byte[] WithAttachments(int amount) { MultiPartEmail email = new MultiPartEmail(); try {//from w ww .j ava 2s. co m email.setFrom(from); email.addTo(to); email.setSubject(subject); email.setMsg(message); email.setHostName(hostName); int x = 1; while (x <= amount) { // Create an attachment with the pom.xml being used to compile (yay!!!) EmailAttachment attachment = new EmailAttachment(); attachment.setPath("pom.xml"); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("pom.xml"); attachment.setName("pom.xml" + String.valueOf(x)); // attach email.attach(attachment); x++; } email.buildMimeMessage(); } catch (EmailException e) { e.printStackTrace(); } ByteArrayOutputStream output = new ByteArrayOutputStream(); MimeMessage mimeMessage = email.getMimeMessage(); try { mimeMessage.writeTo(output); } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } return output.toByteArray(); }
From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java
@SuppressWarnings("unchecked") public void onMessage(Message message) { try {//from w w w . ja v a2 s . c o m LOGGER.debug("Started handling email jms message."); String nodePath = message.getStringProperty(NODE_PATH_PROPERTY); String contentPath = message.getStringProperty(CONTENT_PATH_PROPERTY); Object objRcpt = message.getObjectProperty(RECIPIENTS); List<String> recipients = null; if (objRcpt instanceof List<?>) { recipients = (List<String>) objRcpt; } else if (objRcpt instanceof String) { recipients = new LinkedList<String>(); String[] rcpts = StringUtils.split((String) objRcpt, ','); for (String rcpt : rcpts) { recipients.add(rcpt); } } if (contentPath != null && contentPath.length() > 0) { javax.jcr.Session adminSession = repository.loginAdministrative(null); org.sakaiproject.nakamura.api.lite.Session sparseSession = StorageClientUtils .adaptToSession(adminSession); try { ContentManager contentManager = sparseSession.getContentManager(); Content messageContent = contentManager.get(contentPath); if (objRcpt != null) { // validate the message if (messageContent != null) { if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX) && (MessageConstants.BOX_OUTBOX.equals( messageContent.getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)) || MessageConstants.BOX_PENDING.equals(messageContent .getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)))) { if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) { // We're retrying this message, so clear the errors messageContent.setProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR, (String) null); } if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_TO) && messageContent.hasProperty(MessageConstants.PROP_SAKAI_FROM)) { // make a commons-email message from the message MultiPartEmail email = null; try { email = constructMessage(messageContent, recipients, adminSession, sparseSession); setOptions(email); if (LOGGER.isDebugEnabled()) { // build wrapped meesage in order to log it email.buildMimeMessage(); logEmail(email); } email.send(); } catch (EmailException e) { String exMessage = e.getMessage(); Throwable cause = e.getCause(); setError(messageContent, exMessage); LOGGER.warn("Unable to send email: " + exMessage); // Get the SMTP error code // There has to be a better way to do this boolean rescheduled = false; if (cause != null && cause.getMessage() != null) { String smtpError = cause.getMessage().trim(); try { int errorCode = Integer.parseInt(smtpError.substring(0, 3)); // All retry-able SMTP errors should have codes starting // with 4 scheduleRetry(errorCode, messageContent); rescheduled = true; } catch (NumberFormatException nfe) { // smtpError didn't start with an error code, let's dig for // it String searchFor = "response:"; int rindex = smtpError.indexOf(searchFor); if (rindex > -1 && (rindex + searchFor.length()) < smtpError.length()) { int errorCode = Integer.parseInt(smtpError .substring(searchFor.length(), searchFor.length() + 3)); scheduleRetry(errorCode, messageContent); rescheduled = true; } else if (!rescheduled && cause.toString().contains("java.net.ConnectException")) { scheduleRetry(messageContent); rescheduled = true; } } } if (rescheduled) { LOGGER.info("Email {} rescheduled for redelivery. ", nodePath); } else { LOGGER.error( "Unable to reschedule email for delivery: " + e.getMessage(), e); } } } else { setError(messageContent, "Message must have a to and from set"); } } else { setError(messageContent, "Not an outbox"); } if (!messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) { messageContent.setProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX, MessageConstants.BOX_SENT); } } } else { String retval = "null"; setError(messageContent, "Expected recipients to be String or List<String>. Found " + retval); } } finally { if (adminSession != null) { adminSession.logout(); } } } } catch (PathNotFoundException e) { LOGGER.error(e.getMessage(), e); } catch (RepositoryException e) { LOGGER.error(e.getMessage(), e); } catch (JMSException e) { LOGGER.error(e.getMessage(), e); } catch (EmailDeliveryException e) { LOGGER.error(e.getMessage()); } catch (ClientPoolException e) { LOGGER.error(e.getMessage(), e); } catch (StorageClientException e) { LOGGER.error(e.getMessage(), e); } catch (AccessDeniedException e) { LOGGER.error(e.getMessage(), e); } }
From source file:org.viafirma.util.SendMailUtil.java
/** * Crea el MIME mensaje aadiendo su contenido, y su destinatario. * @param contentType // w w w.java 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; }