List of usage examples for javax.activation DataHandler DataHandler
public DataHandler(URL url)
DataHandler
instance referencing a URL. From source file:org.latticesoft.util.resource.MessageUtil.java
/** * Sends the email.// www. ja va 2s . c om * @param info the EmailInfo containing the message and other details * @param p the properties to set in the environment when instantiating the session * @param auth the authenticator */ public static void sendMail(EmailInfo info, Properties p, Authenticator auth) { try { if (p == null) { if (log.isErrorEnabled()) { log.error("Null properties!"); } return; } Session session = Session.getInstance(p, auth); session.setDebug(true); if (log.isInfoEnabled()) { log.info(p); log.info(session); } MimeMessage mimeMessage = new MimeMessage(session); if (log.isInfoEnabled()) { log.info(mimeMessage); log.info(info.getFromAddress()); } mimeMessage.setFrom(info.getFromAddress()); mimeMessage.setSentDate(new Date()); List l = info.getToList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); if (log.isInfoEnabled()) { log.info(addr); } mimeMessage.addRecipients(Message.RecipientType.TO, addr); } } l = info.getCcList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.CC, addr); } } l = info.getBccList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.BCC, addr); } } if (info.getAttachment().size() == 0) { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); mimeMessage.setText(info.getContent(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); mimeMessage.setText(info.getContent()); } mimeMessage.setContent(info.getContent(), info.getContentType()); } else { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); } Multipart mp = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); if (info.getCharSet() != null) { body.setText(info.getContent(), info.getCharSet()); body.setContent(info.getContent(), info.getContentType()); } else { body.setText(info.getContent()); body.setContent(info.getContent(), info.getContentType()); } mp.addBodyPart(body); for (int i = 0; i < info.getAttachment().size(); i++) { String filename = (String) info.getAttachment().get(i); MimeBodyPart attachment = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); attachment.setDataHandler(new DataHandler(fds)); attachment.setFileName(MimeUtility.encodeWord(fds.getName())); mp.addBodyPart(attachment); } mimeMessage.setContent(mp); } Transport.send(mimeMessage); } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Error in sending email", e); } } }
From source file:com.enonic.esl.net.Mail.java
/** * <p/> Send the mail. The SMTP host is contacted and the mail is sent according to the parameters set. </p> <p/> If it fails, it is * considered a runtime exception. Note that this doesn't make it very failsafe, so care should be taken when one wants fault tolerance. * One solution could be to catch the exception thrown. Another solution could be to use the JavaMail API directly. </p> *//* w w w. j a v a2 s. c om*/ public void send() throws ESLException { // smtp server Properties smtpProperties = new Properties(); if (smtpHost != null) { smtpProperties.put("mail.smtp.host", smtpHost); System.setProperty("mail.smtp.host", smtpHost); } else { smtpProperties.put("mail.smtp.host", DEFAULT_SMTPHOST); System.setProperty("mail.smtp.host", DEFAULT_SMTPHOST); } Session session = Session.getDefaultInstance(smtpProperties, null); try { // create message Message msg = new MimeMessage(session); // set from address InternetAddress addressFrom = new InternetAddress(); if (from_email != null) { addressFrom.setAddress(from_email); } if (from_name != null) { addressFrom.setPersonal(from_name, ENCODING); } ((MimeMessage) msg).setFrom(addressFrom); if ((to.size() == 0 && bcc.size() == 0) || subject == null || (message == null && htmlMessage == null)) { LOG.error("Missing data. Unable to send mail."); throw new ESLException("Missing data. Unable to send mail."); } // set to: for (int i = 0; i < to.size(); ++i) { String[] recipient = to.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.TO, addressTo); } // set bcc: for (int i = 0; i < bcc.size(); ++i) { String[] recipient = bcc.get(i); InternetAddress addressTo = null; try { addressTo = new InternetAddress(recipient[1]); } catch (Exception e) { System.err.println("exception on address: " + recipient[1]); continue; } if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.BCC, addressTo); } // set cc: for (int i = 0; i < cc.size(); ++i) { String[] recipient = cc.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.CC, addressTo); } // Setting subject and content type ((MimeMessage) msg).setSubject(subject, ENCODING); if (message != null) { message = RegexpUtil.substituteAll("\\\\n", "\n", message); } // if there are any attachments, treat this as a multipart message. if (attachments.size() > 0) { BodyPart messageBodyPart = new MimeBodyPart(); if (message != null) { ((MimeBodyPart) messageBodyPart).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeBodyPart) messageBodyPart).setDataHandler(dataHandler); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // add all attachments for (int i = 0; i < attachments.size(); ++i) { Object obj = attachments.get(i); if (obj instanceof String) { System.err.println("attachment is String"); messageBodyPart = new MimeBodyPart(); ((MimeBodyPart) messageBodyPart).setText((String) obj, ENCODING); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof File) { messageBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource((File) obj); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof FileItem) { FileItem fileItem = (FileItem) obj; messageBodyPart = new MimeBodyPart(); FileItemDataSource fds = new FileItemDataSource(fileItem); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else { // byte array messageBodyPart = new MimeBodyPart(); ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) obj, "text/html", ENCODING); messageBodyPart.setDataHandler(new DataHandler(bads)); messageBodyPart.setFileName(bads.getName()); multipart.addBodyPart(messageBodyPart); } } msg.setContent(multipart); } else { if (message != null) { ((MimeMessage) msg).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeMessage) msg).setDataHandler(dataHandler); } } // send message Transport.send(msg); } catch (AddressException e) { String MESSAGE_30 = "Error in email address: " + e.getMessage(); LOG.warn(MESSAGE_30); throw new ESLException(MESSAGE_30, e); } catch (UnsupportedEncodingException e) { String MESSAGE_40 = "Unsupported encoding: " + e.getMessage(); LOG.error(MESSAGE_40, e); throw new ESLException(MESSAGE_40, e); } catch (SendFailedException sfe) { Throwable t = null; Exception e = sfe.getNextException(); while (e != null) { t = e; if (t instanceof SendFailedException) { e = ((SendFailedException) e).getNextException(); } else { e = null; } } if (t != null) { String MESSAGE_50 = "Error sending mail: " + t.getMessage(); throw new ESLException(MESSAGE_50, t); } else { String MESSAGE_50 = "Error sending mail: " + sfe.getMessage(); throw new ESLException(MESSAGE_50, sfe); } } catch (MessagingException e) { String MESSAGE_50 = "Error sending mail: " + e.getMessage(); LOG.error(MESSAGE_50, e); throw new ESLException(MESSAGE_50, e); } }
From source file:org.sventon.mail.MailNotifier.java
/** * @param logEntry Log entry//from w ww. java 2 s. c o m * @param repositoryName Name * @param mailTemplate Template * @return Message * @throws MessagingException If a message exception occurs. * @throws IOException if a IO exception occurs while creating the data source. */ private Message createMessage(final LogEntry logEntry, RepositoryName repositoryName, String mailTemplate) throws MessagingException, IOException { final Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.BCC, receivers.toArray(new InternetAddress[receivers.size()])); msg.setSubject(formatSubject(subject, logEntry.getRevision(), repositoryName)); msg.setDataHandler( new DataHandler(new ByteArrayDataSource(HTMLCreator.createRevisionDetailBody(mailTemplate, logEntry, baseURL, repositoryName, dateFormat, null), "text/html"))); msg.setHeader("X-Mailer", "sventon"); msg.setSentDate(new Date()); return msg; }
From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java
private static void setFileAsAttachment(Message msg, String message, File file) throws MessagingException { MimeBodyPart p1 = new MimeBodyPart(); p1.setText(message);/*w w w.ja va2 s.com*/ // Create second part MimeBodyPart p2 = new MimeBodyPart(); // Put a file in the second part FileDataSource fds = new FileDataSource(file); p2.setDataHandler(new DataHandler(fds)); p2.setFileName(fds.getName()); // Create the Multipart. Add BodyParts to it. Multipart mp = new MimeMultipart(); mp.addBodyPart(p1); mp.addBodyPart(p2); // Set Multipart as the message's content msg.setContent(mp); }
From source file:edu.jhu.cvrg.waveform.utility.WebServiceUtility.java
private static void addFiles(Map<String, FSFile> filesMap, OMElement omWebService, OMFactory omFactory, OMNamespace omNamespace) {/* ww w . j a v a 2 s . c o m*/ if (filesMap != null) { StringBuilder filesId = new StringBuilder(); for (String key : filesMap.keySet()) { OMElement fileElement = omFactory.createOMElement("file_" + key, omNamespace); FSFile file = filesMap.get(key); DataHandler dh = new DataHandler(new ByteArrayDataSource(file.getFileDataAsBytes())); OMText textData = omFactory.createOMText(dh, true); fileElement.addChild(textData); omWebService.addChild(fileElement); filesId.append(file.getId()).append(','); } addOMEChild("filesId", filesId.toString(), omWebService); } }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private void includeAttachments(MimeMultipart mimeMultipart, List<LabelValueBean> attachments) throws MessagingException { for (int i = 0; i < attachments.size(); i++) { LabelValueBean lvb = attachments.get(i); File f = new File(lvb.getValue()); if (f != null && f.exists()) { LOGGER.debug("Use attachment file:" + f.getAbsolutePath()); MimeBodyPart mbpFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(lvb.getLabel()); mimeMultipart.addBodyPart(mbpFile); } else {//from ww w .j a v a 2 s.c o m LOGGER.debug("Attachment file:\"" + lvb.getValue() + "\" not exits!"); } } }
From source file:org.sventon.repository.observer.MailNotifier.java
/** * @param logEntry Log entry//w ww .jav a 2s . com * @param repositoryName Name * @param mailTemplate Template * @return Message * @throws MessagingException If a message exception occurs. * @throws IOException if a IO exception occurs while creating the data source. */ private Message createMessage(final SVNLogEntry logEntry, RepositoryName repositoryName, String mailTemplate) throws MessagingException, IOException { final Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.BCC, receivers.toArray(new InternetAddress[receivers.size()])); msg.setSubject(formatSubject(subject, logEntry.getRevision(), repositoryName)); msg.setDataHandler( new DataHandler(new ByteArrayDataSource(HTMLCreator.createRevisionDetailBody(mailTemplate, logEntry, baseUrl, repositoryName, dateFormat, null), "text/html"))); msg.setHeader("X-Mailer", "sventon"); msg.setSentDate(new Date()); return msg; }
From source file:org.unitime.commons.Email.java
public void addAttachement(File file, String name) throws MessagingException { BodyPart attachement = new MimeBodyPart(); attachement.setDataHandler(new DataHandler(new FileDataSource(file))); attachement.setFileName(name == null ? file.getName() : name); iBody.addBodyPart(attachement);//from w w w . j ava 2 s .c om }
From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java
@DirtiesContext @Test//from ww w . j a va2 s . c o m public void testMarshalPdf() throws Exception { Assert.assertNotNull(testShsMessage); Assert.assertNotNull(testPdfFile); testShsMessage.getDataParts().remove(0); DataPart dataPart = new DataPart( new DataHandler(new ByteArrayDataSource(testPdfFile.getInputStream(), "application/xml"))); dataPart.setContentType("application/xml"); dataPart.setFileName(testPdfFile.getFilename()); dataPart.setTransferEncoding("base64"); dataPart.setDataPartType("pdf"); testShsMessage.getDataParts().add(dataPart); resultEndpoint.expectedMessageCount(1); template.sendBody("direct:marshalRoundtrip", testShsMessage); resultEndpoint.assertIsSatisfied(); List<Exchange> exchanges = resultEndpoint.getReceivedExchanges(); Exchange exchange = exchanges.get(0); ShsMessage shsMessage = exchange.getIn().getMandatoryBody(ShsMessage.class); Assert.assertNotSame(shsMessage, testShsMessage); ShsLabel label = shsMessage.getLabel(); Assert.assertNotNull(label, "label should not be null"); Assert.assertEquals(label.getSubject(), testShsMessage.getLabel().getSubject()); Assert.assertEquals(label.getDatetime().toString(), testShsMessage.getLabel().getDatetime().toString()); Assert.assertNotNull(testShsMessage.getDataParts()); DataPart dataPartResponse = testShsMessage.getDataParts().get(0); Assert.assertTrue(isSame(testPdfFile.getInputStream(), dataPartResponse.getDataHandler().getInputStream()), "Response data stream is not same as source data stream"); }
From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java
public void sendMail(Mail mail) { LOG.debug("sendEmail() to: " + mail.getRecipient()); try {/* w w w.j a va2 s . com*/ Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator); session.setDebug(false); MimeMessage msg = new MimeMessage(session); msg.setFrom(m_bag.m_fromAddress); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient())); msg.setSubject(mail.getSubject()); msg.setSentDate(new Date()); Multipart mp = new MimeMultipart(); MimeBodyPart txtmbp = new MimeBodyPart(); txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE); mp.addBodyPart(txtmbp); List<String> attachments = mail.getAttachments(); for (Iterator<String> it = attachments.iterator(); it.hasNext();) { MimeBodyPart mbp = new MimeBodyPart(); String filename = it.next(); FileDataSource fds = new FileDataSource(filename); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeText(fds.getName())); mp.addBodyPart(mbp); } msg.setContent(mp); if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null) && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) { cheat(msg, m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@"))); } Transport.send(msg); LOG.info("Successfully send the mail to " + mail.getRecipient()); } catch (Throwable e) { LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e); LOG.debug("Details:", e); } }