List of usage examples for org.apache.commons.mail Email getMimeMessage
public MimeMessage getMimeMessage()
From source file:de.cosmocode.palava.services.mail.VelocityMailService.java
@Override public MimeMessage sendMessage(String templateName, String lang, Map<String, ?> params, String... to) throws Exception { if (templateName == null) throw new IllegalArgumentException("Template name is null"); final VelocityContext ctx = new VelocityContext(params); final String prefix = StringUtils.isBlank(lang) ? "" : lang + "/"; final Template template = engine.getTemplate(prefix + templateName, CHARSET); final Embedder embed = new Embedder(engine); ctx.put("embed", embed); ctx.put("entity", EntityEncoder.getInstance()); final StringWriter writer = new StringWriter(); template.merge(ctx, writer);//from ww w . ja va 2 s. co m final EmailFactory factory = EmailFactory.getInstance(); final SAXBuilder builder = new SAXBuilder(); final Document document = builder.build(new StringReader(writer.toString())); final Email email = factory.build(document, embed); email.setHostName(hostname); for (String recipient : to) { email.addTo(recipient); } email.send(); return email.getMimeMessage(); }
From source file:gov.nih.nci.firebird.service.messages.email.EmailServiceImpl.java
private void sendEmail(Email email) throws EmailException { initEmailInfo(email);// w w w . j a va 2 s.c om if (sendMail) { email.send(); } else { email.buildMimeMessage(); if (LOG.isDebugEnabled()) { LOG.debug("Email Sending is off. " + email.getMimeMessage()); } } }
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!/*from w w w. j a v a 2 s . c o m*/ * * @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 ww w .j a v a2 s . c o m * * @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:org.apache.nifi.processors.email.GenerateAttachment.java
public byte[] SimpleEmail() { Email email = new SimpleEmail(); try {//from w w w.j ava 2 s . c om email.setFrom(from); email.addTo(to); email.setSubject(subject); email.setMsg(message); email.setHostName(hostName); 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.apache.sling.commons.messaging.mail.internal.SimpleMailBuilderIT.java
@Test public void testBuildWithDefaults() throws Exception { final MailBuilder mailBuilder = getService(MailBuilder.class); final Email email = mailBuilder.build("Stop your messing around, Better think of your future...", "rudy@ghosttown", Collections.emptyMap()); email.buildMimeMessage();//from ww w . j a v a2 s. c om final byte[] bytes = MailUtil.toByteArray(email); final String mail = new String(bytes, StandardCharsets.UTF_8); logger.debug("mail: " + mail); assertEquals("rudy@ghosttown", email.getToAddresses().get(0).getAddress()); assertEquals("Rudy, A Message to You", email.getSubject()); assertEquals("dandy.livingstone@kingston.jamaica", email.getFromAddress().getAddress()); assertEquals("localhost", email.getHostName()); logger.debug(email.getMimeMessage().getContent().toString()); }
From source file:org.apache.sling.commons.messaging.mail.internal.SimpleMailBuilderIT.java
@Test public void testBuildWithData() throws Exception { final MailBuilder mailBuilder = getService(MailBuilder.class); final Map<String, String> configuration = new HashMap<>(); configuration.put("mail.subject", "Rudy, A Message to You"); configuration.put("mail.from", "specials@thespecials.com"); final Map data = Collections.singletonMap("mail", configuration); final Email email = mailBuilder.build("A Message to You, Rudy", "rudy@ghosttown", data); email.buildMimeMessage();/*from ww w .j a va 2s . co m*/ final byte[] bytes = MailUtil.toByteArray(email); final String mail = new String(bytes, StandardCharsets.UTF_8); logger.debug("mail: " + mail); assertEquals("rudy@ghosttown", email.getToAddresses().get(0).getAddress()); assertEquals("Rudy, A Message to You", email.getSubject()); assertEquals("specials@thespecials.com", email.getFromAddress().getAddress()); assertEquals("localhost", email.getHostName()); logger.debug(email.getMimeMessage().getContent().toString()); }
From source file:org.apache.sling.commons.messaging.mail.MailUtil.java
public static byte[] toByteArray(final Email email) throws IOException, MessagingException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); email.getMimeMessage().writeTo(baos); return baos.toByteArray(); }
From source file:org.oscarehr.util.EmailUtils.java
/** * This method is like a toString for Email objects. *//*from w ww .j a v a 2 s . c om*/ public static String getAsString(Email email) throws IOException, MessagingException, EmailException { email.buildMimeMessage(); return (getAsString(email.getMimeMessage())); }
From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java
public void testCommonsEmailOneWaySeparateSessions() { Queue emailQueue = null;/*w w w . j av a 2 s. c om*/ MessageConsumer consumer = null; MessageProducer producer = null; Session clientSession = null; Session listenerSession = null; // it is not necessary to use the Email interface here // Email is used here just to allow for multiple types of emails to // occupy // the same varaible. SimpleEmail etc can each be used directly. List<Email> emails = new ArrayList<Email>(); EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null, null, null, null); emails.add(new SimpleEmail(messagingService)); emails.add(new MultiPartEmail(messagingService)); emails.add(new HtmlEmail(messagingService)); try { listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = listenerSession.createQueue(emailQueueName); consumer = listenerSession.createConsumer(emailQueue); consumer.setMessageListener(new EmailListener()); listenerConn.start(); listenerSession.run(); } catch (JMSException e2) { e2.printStackTrace(); Assert.assertTrue(false); } Wiser smtpServer = new Wiser(); smtpServer.setPort(smtpTestPort); smtpServer.start(); try { clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = clientSession.createQueue(emailQueueName); producer = clientSession.createProducer(emailQueue); clientConn.start(); clientSession.run(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } for (Email em : emails) { try { em.addTo(TEST_EMAIL_TO); em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL); // host and port will be ignored since the email session is // established // by // the listener em.setHostName("localhost"); em.setSmtpPort(smtpTestPort); em.setSubject(TEST_EMAIL_SUBJECT); if (em instanceof HtmlEmail) { em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL); } else if (em instanceof MultiPartEmail) { em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL); } else if (em instanceof SimpleEmail) { em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL); } } catch (EmailException e1) { Assert.assertTrue(false); e1.printStackTrace(); } try { em.buildMimeMessage(); } catch (EmailException e1) { e1.printStackTrace(); Assert.assertTrue(false); } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { em.getMimeMessage().writeTo(os); } catch (javax.mail.MessagingException e) { e.printStackTrace(); Assert.assertTrue(false); } catch (IOException e) { e.printStackTrace(); Assert.assertTrue(false); } String content = os.toString(); ObjectMessage om; try { om = clientSession.createObjectMessage(content); om.setJMSType(emailType); LOG.info("Client: Sending test message...."); producer.send(om); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } } long start = System.currentTimeMillis(); while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) { // wait for transport } Assert.assertTrue(listenerMessagesProcessed == 3); List<WiserMessage> messages = smtpServer.getMessages(); Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3); for (WiserMessage wisermsg : messages) { String body = null; String subject = null; MimeMessage testmail = null; try { testmail = wisermsg.getMimeMessage(); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } if (testmail != null) { LOG.info("SMTP server: test email received: "); try { LOG.info("To: " + testmail.getHeader("To", ",")); LOG.info("Subject: " + testmail.getHeader("Subject", ",")); body = getBodyAsString(testmail.getContent()); subject = testmail.getHeader("Subject", ","); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } catch (IOException e) { Assert.assertTrue(false); e.printStackTrace(); } LOG.info("Body: " + body); Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT)); Assert.assertTrue(body.contains("This is a Commons")); } else { Assert.assertTrue(false); } } if (clientSession != null) { try { clientSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } clientSession = null; } if (listenerSession != null) { try { listenerSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } listenerSession = null; } smtpServer.stop(); }