List of usage examples for javax.mail.internet MimeBodyPart setDataHandler
@Override public void setDataHandler(DataHandler dh) throws MessagingException
From source file:sendfile.java
public static void main(String[] args) { if (args.length != 5) { System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false"); System.exit(1);// w ww .j av a2 s. c o m } String to = args[0]; String from = args[1]; String host = args[2]; String filename = args[3]; boolean debug = Boolean.valueOf(args[4]).booleanValue(); String msgText1 = "Sending a file.\n"; String subject = "Sending a file"; // create some properties and get the default Session Properties props = System.getProperties(); props.put("mail.smtp.host", host); Session session = Session.getInstance(props, null); session.setDebug(debug); try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msgText1); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(filename); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // send the message Transport.send(msg); } catch (MessagingException mex) { mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); } } }
From source file:com.googlecode.psiprobe.tools.Mailer.java
private static MimeBodyPart createAttachmentPart(DataSource attachment) throws MessagingException { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(attachment)); attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT); attachmentPart.setFileName(attachment.getName()); return attachmentPart; }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.AttachmentUtils.java
public static boolean prepareRequestPart(WsdlRequest wsdlRequest, MimeMultipart mp, RequestXmlPart requestPart, StringToStringMap contentIds) throws Exception, MessagingException { boolean isXop = false; XmlCursor cursor = requestPart.newCursor(); try {//from w ww . j a v a 2 s . c o m while (!cursor.isEnddoc()) { if (cursor.isContainer()) { // could be an attachment part (as of "old" SwA specs which specify a content // element referring to the attachment) if (requestPart.isAttachmentPart()) { String href = cursor.getAttributeText(new QName("href")); if (href != null && href.length() > 0) { contentIds.put(requestPart.getPart().getName(), href); } break; } SchemaType schemaType = cursor.getObject().schemaType(); if (isBinaryType(schemaType)) { String contentType = getXmlMimeContentType(cursor); // extract contentId String textContent = cursor.getTextValue(); Attachment attachment = null; boolean isXopAttachment = false; // is content a reference to a file? if (textContent.startsWith("file:")) { String filename = textContent.substring(5); if (contentType == null) { inlineData(cursor, schemaType, new FileInputStream(filename)); } else if (wsdlRequest.isMtomEnabled()) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); part.setDataHandler(new DataHandler( new XOPPartDataSource(new File(filename), contentType, schemaType))); part.setContentID("<" + filename + ">"); mp.addBodyPart(part); isXopAttachment = true; } } // is content a reference to an attachment? else if (textContent.startsWith("cid:")) { textContent = textContent.substring(4); Attachment[] attachments = wsdlRequest.getAttachmentsForPart(textContent); if (attachments.length == 1) { attachment = attachments[0]; } else if (attachments.length > 1) { attachment = buildMulitpartAttachment(attachments); } isXopAttachment = contentType != null; contentIds.put(textContent, textContent); } // content should be binary data; is this an XOP element which should be serialized with MTOM? else if (wsdlRequest.isMtomEnabled() && contentType != null) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); part.setDataHandler( new DataHandler(new XOPPartDataSource(textContent, contentType, schemaType))); textContent = "http://www.soapui.org/" + System.nanoTime(); part.setContentID("<" + textContent + ">"); mp.addBodyPart(part); isXopAttachment = true; } // add XOP include? if (isXopAttachment && wsdlRequest.isMtomEnabled()) { buildXopInclude(cursor, textContent); isXop = true; } // inline? else if (attachment != null) { inlineAttachment(cursor, schemaType, attachment); } } } cursor.toNextToken(); } } finally { cursor.dispose(); } return isXop; }
From source file:org.latticesoft.util.resource.MessageUtil.java
/** * Sends the email.// www.ja v a 2 s . co m * @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.medsavant.mailer.Mail.java
public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) { try {/*from ww w . j a v a 2s .c o m*/ if (src == null || pw == null || host == null || port == -1) { return false; } if (to.isEmpty()) { return false; } LOG.info("Sending email to " + to + " with subject " + subject); // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.user", src); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.starttls.enable", starttls); props.put("mail.smtp.auth", auth); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", socketFactoryClass); props.put("mail.smtp.socketFactory.fallback", fallback); Session session = Session.getInstance(props, null); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(src, srcName)); InternetAddress[] address = InternetAddress.parse(to); msg.setRecipients(Message.RecipientType.BCC, address); msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(text, "text/html"); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); if (attachment != null) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); mp.addBodyPart(mbp2); } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // send the message Transport transport = session.getTransport("smtp"); transport.connect(host, src, pw); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); LOG.info("Mail sent"); return true; } catch (Exception ex) { ex.printStackTrace(); LOG.error(ex); return false; } }
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);//ww w .java 2s .c om // 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:org.apache.axiom.om.impl.MIMEOutputUtils.java
/** * @deprecated This method is only useful in conjunction with * {@link #writeBodyPart(OutputStream, MimeBodyPart, String)}, which is deprecated. */// w ww.j ava 2s. c o m public static MimeBodyPart createMimeBodyPart(String contentID, DataHandler dataHandler, OMOutputFormat omOutputFormat) throws MessagingException { String contentType = dataHandler.getContentType(); // Get the content-transfer-encoding String contentTransferEncoding = "binary"; if (dataHandler instanceof ConfigurableDataHandler) { ConfigurableDataHandler configurableDataHandler = (ConfigurableDataHandler) dataHandler; contentTransferEncoding = configurableDataHandler.getTransferEncoding(); } if (isDebugEnabled) { log.debug("Create MimeBodyPart"); log.debug(" Content-ID = " + contentID); log.debug(" Content-Type = " + contentType); log.debug(" Content-Transfer-Encoding = " + contentTransferEncoding); } boolean useCTEBase64 = omOutputFormat != null && Boolean.TRUE .equals(omOutputFormat.getProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS)); if (useCTEBase64) { if (!CommonUtils.isTextualPart(contentType) && "binary".equals(contentTransferEncoding)) { if (isDebugEnabled) { log.debug( " changing Content-Transfer-Encoding from " + contentTransferEncoding + " to base-64"); } contentTransferEncoding = "base64"; } } // Now create the mimeBodyPart for the datahandler and add the appropriate content headers MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setDataHandler(dataHandler); mimeBodyPart.addHeader("Content-ID", "<" + contentID + ">"); mimeBodyPart.addHeader("Content-Type", contentType); mimeBodyPart.addHeader("Content-Transfer-Encoding", contentTransferEncoding); return mimeBodyPart; }
From source file:org.vosao.utils.EmailUtil.java
/** * Send email with html content and attachments. * @param htmlBody// w ww . ja v a2 s . c om * @param subject * @param fromAddress * @param fromText * @param toAddress * @return null if OK or error message. */ public static String sendEmail(final String htmlBody, final String subject, final String fromAddress, final String fromText, final String toAddress, final List<FileItem> files) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try { Multipart mp = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlBody, "text/html"); htmlPart.setHeader("Content-type", "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); for (FileItem item : files) { MimeBodyPart attachment = new MimeBodyPart(); attachment.setFileName(item.getFilename()); String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename())); DataSource ds = new ByteArrayDataSource(item.getData(), mimeType); attachment.setDataHandler(new DataHandler(ds)); mp.addBodyPart(attachment); } MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress, fromText)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress)); msg.setSubject(subject, "UTF-8"); msg.setContent(mp); Transport.send(msg); return null; } catch (AddressException e) { return e.getMessage(); } catch (MessagingException e) { return e.getMessage(); } catch (UnsupportedEncodingException e) { return e.getMessage(); } }
From source file:org.apache.axiom.om.impl.MIMEOutputUtils.java
/** * @deprecated Use {@link OMMultipartWriter} instead. *//*from w w w .j av a2 s . c om*/ public static void complete(OutputStream outStream, byte[] xmlData, LinkedList binaryNodeList, String boundary, String contentId, String charSetEncoding, String SOAPContentType, OMOutputFormat omOutputFormat) { try { if (isDebugEnabled) { log.debug("Start: write the SOAPPart and the attachments"); } // Write out the mime boundary startWritingMime(outStream, boundary); javax.activation.DataHandler dh = new javax.activation.DataHandler( new ByteArrayDataSource(xmlData, "text/xml; charset=" + charSetEncoding)); MimeBodyPart rootMimeBodyPart = new MimeBodyPart(); rootMimeBodyPart.setDataHandler(dh); rootMimeBodyPart.addHeader("Content-Type", "application/xop+xml; charset=" + charSetEncoding + "; type=\"" + SOAPContentType + "\""); rootMimeBodyPart.addHeader("Content-Transfer-Encoding", "binary"); rootMimeBodyPart.addHeader("Content-ID", "<" + contentId + ">"); // Write out the SOAPPart writeBodyPart(outStream, rootMimeBodyPart, boundary); // Now write out the Attachment parts (which are represented by the // text nodes int the binary node list) Iterator binaryNodeIterator = binaryNodeList.iterator(); while (binaryNodeIterator.hasNext()) { OMText binaryNode = (OMText) binaryNodeIterator.next(); writeBodyPart(outStream, createMimeBodyPart(binaryNode.getContentID(), (DataHandler) binaryNode.getDataHandler(), omOutputFormat), boundary); } finishWritingMime(outStream); outStream.flush(); if (isDebugEnabled) { log.debug("End: write the SOAPPart and the attachments"); } } catch (IOException e) { throw new OMException("Error while writing to the OutputStream.", e); } catch (MessagingException e) { throw new OMException("Problem writing Mime Parts.", e); } }
From source file:org.apache.hupa.server.utils.MessageUtils.java
/** * Convert a FileItem to a BodyPart/*www. j a v a 2s . c o m*/ * * @param item * @return message body part * @throws MessagingException */ public static BodyPart fileitemToBodypart(FileItem item) throws MessagingException { MimeBodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileItemDataStore(item); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(source.getName()); return messageBodyPart; }