List of usage examples for javax.mail BodyPart setDisposition
public void setDisposition(String disposition) throws MessagingException;
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }//ww w.j ava 2 s. c om if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;//from w w w . j a v a 2 s . co m props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java
public MimeMessageHelper addAttachment(String name, String type, byte[] content) throws MessagingException { BodyPart attachmentPart = new MimeBodyPart(); ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(content, type); attachmentPart.setDataHandler(new DataHandler(byteArrayDataSource)); attachmentPart.setFileName(name);/* ww w. ja va 2s . c om*/ attachmentPart.setDisposition(Part.ATTACHMENT); attachments.add(attachmentPart); return this; }
From source file:immf.ImodeForwardMail.java
private void attacheFile() throws EmailException { try {//from w w w .ja v a2s . com List<AttachedFile> files = this.imm.getAttachFileList(); for (AttachedFile f : files) { BodyPart part = createBodyPart(); part.setDataHandler(new DataHandler(new ByteArrayDataSource(f.getData(), f.getContentType()))); Util.setFileName(part, f.getFilename(), this.charset, null); part.setDisposition(BodyPart.ATTACHMENT); getContainer().addBodyPart(part); } } catch (Exception e) { throw new EmailException(e); } }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Send a Multipart text message with attached files. FIXME: use * prepareMessage method// w w w .j av a2 s .c om * * @param strRecipientsTo * The list of the main recipients email.Every recipient must be * separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param fileAttachements * The list of attached files * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occured */ protected static void sendMultipartMessageText(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, List<FileAttachment> fileAttachements, Transport transport, Session session) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session); msg.setHeader(HEADER_NAME, HEADER_VALUE); // Creation of the root part containing all the elements of the message MimeMultipart multipart = new MimeMultipart(); // Creation of the html part, the "core" of the message BodyPart msgBodyPart = new MimeBodyPart(); // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE ); msgBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_PLAIN) + AppPropertiesService.getProperty(PROPERTY_CHARSET)))); multipart.addBodyPart(msgBodyPart); // add File Attachement if (fileAttachements != null) { for (FileAttachment fileAttachement : fileAttachements) { String strFileName = fileAttachement.getFileName(); byte[] bContentFile = fileAttachement.getData(); String strContentType = fileAttachement.getType(); ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType); msgBodyPart = new MimeBodyPart(); msgBodyPart.setDataHandler(new DataHandler(dataSource)); msgBodyPart.setFileName(strFileName); msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT); multipart.addBodyPart(msgBodyPart); } } msg.setContent(multipart); sendMessage(msg, transport); }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private void includeImageLogo(MimeMultipart mimeMultipart) { BodyPart messageBodyPart; ArrayList<String> imageFiles = new ArrayList<String>(); imageFiles.add("tracklogo.gif"); // more images can be added here ArrayList<String> cids = new ArrayList<String>(); cids.add("logo"); // for each image there should be a cid here URL imageURL = null;// w w w .j a va 2 s.com for (int i = 0; i < imageFiles.size(); ++i) { try { DataSource ds = null; messageBodyPart = new MimeBodyPart(); InputStream in = null; in = ImageAction.class.getClassLoader().getResourceAsStream(imageFiles.get(i)); int length = imageFiles.get(i).length(); String type = imageFiles.get(i).substring(length - 4, length - 1); if (in != null) { ds = new ByteArrayDataSource(in, "image/" + type); System.err.println(type); } else { String theResource = "/WEB-INF/classes/resources/MailTemplates/" + imageFiles.get(i); imageURL = servletContext.getResource(theResource); ds = new URLDataSource(imageURL); } messageBodyPart.setDataHandler(new DataHandler(ds)); messageBodyPart.setHeader("Content-ID", cids.get(i)); messageBodyPart.setDisposition("inline"); // add it mimeMultipart.addBodyPart(messageBodyPart); } catch (Exception e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); // what shall we do here? } } }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Send a Multipart HTML message with the attachements associated to the * message and attached files. FIXME: use prepareMessage method * * @param strRecipientsTo/*from w w w .ja va2s. c o m*/ * The list of the main recipients email.Every recipient must be * separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param urlAttachements * The List of UrlAttachement Object, containing the URL of * attachments associated with their content-location. * @param fileAttachements * The list of files attached * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occurred */ protected static void sendMultipartMessageHtml(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, List<UrlAttachment> urlAttachements, List<FileAttachment> fileAttachements, Transport transport, Session session) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session); msg.setHeader(HEADER_NAME, HEADER_VALUE); // Creation of the root part containing all the elements of the message MimeMultipart multipart = ((fileAttachements == null) || (fileAttachements.isEmpty())) ? new MimeMultipart(MULTIPART_RELATED) : new MimeMultipart(); // Creation of the html part, the "core" of the message BodyPart msgBodyPart = new MimeBodyPart(); // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE ); msgBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML) + AppPropertiesService.getProperty(PROPERTY_CHARSET)))); multipart.addBodyPart(msgBodyPart); if (urlAttachements != null) { ByteArrayDataSource urlByteArrayDataSource; for (UrlAttachment urlAttachement : urlAttachements) { urlByteArrayDataSource = convertUrlAttachmentDataSourceToByteArrayDataSource(urlAttachement); if (urlByteArrayDataSource != null) { msgBodyPart = new MimeBodyPart(); // Fill this part, then add it to the root part with the // good headers msgBodyPart.setDataHandler(new DataHandler(urlByteArrayDataSource)); msgBodyPart.setHeader(HEADER_CONTENT_LOCATION, urlAttachement.getContentLocation()); multipart.addBodyPart(msgBodyPart); } } } // add File Attachement if (fileAttachements != null) { for (FileAttachment fileAttachement : fileAttachements) { String strFileName = fileAttachement.getFileName(); byte[] bContentFile = fileAttachement.getData(); String strContentType = fileAttachement.getType(); ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType); msgBodyPart = new MimeBodyPart(); msgBodyPart.setDataHandler(new DataHandler(dataSource)); msgBodyPart.setFileName(strFileName); msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT); multipart.addBodyPart(msgBodyPart); } } msg.setContent(multipart); sendMessage(msg, transport); }
From source file:org.apache.axis2.transport.mail.EMailSender.java
private void createMailMimeMessage(final MimeMessage msg, MailToInfo mailToInfo, OMOutputFormat format) throws MessagingException { // Create the message part BodyPart messageBodyPart = new MimeBase64BodyPart(); messageBodyPart.setText(""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); DataSource source = null;//w ww . j a v a2s . c om // Part two is attachment if (outputStream instanceof ByteArrayOutputStream) { source = new ByteArrayDataSource(((ByteArrayOutputStream) outputStream).toByteArray()); } messageBodyPart = new MimeBase64BodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setDisposition(Part.ATTACHMENT); messageBodyPart.addHeader("Content-Description", "\"" + mailToInfo.getContentDescription() + "\""); String contentType = format.getContentType() != null ? format.getContentType() : Constants.DEFAULT_CONTENT_TYPE; if (contentType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) { if (messageContext.getSoapAction() != null) { messageBodyPart.setHeader(Constants.HEADER_SOAP_ACTION, messageContext.getSoapAction()); } } if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) { if (messageContext.getSoapAction() != null) { messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding() + " ; action=\"" + messageContext.getSoapAction() + "\""); } } else { messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding()); } multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); }
From source file:org.apache.camel.component.mail.MailBinding.java
protected void addAttachmentsToMultipart(MimeMultipart multipart, String partDisposition, Exchange exchange) throws MessagingException { LOG.trace("Adding attachments +++ start +++"); int i = 0;//from w ww. j av a 2 s . c om for (Map.Entry<String, DataHandler> entry : exchange.getIn().getAttachments().entrySet()) { String attachmentFilename = entry.getKey(); DataHandler handler = entry.getValue(); if (LOG.isTraceEnabled()) { LOG.trace("Attachment #" + i + ": Disposition: " + partDisposition); LOG.trace("Attachment #" + i + ": DataHandler: " + handler); LOG.trace("Attachment #" + i + ": FileName: " + attachmentFilename); } if (handler != null) { if (shouldAddAttachment(exchange, attachmentFilename, handler)) { // Create another body part BodyPart messageBodyPart = new MimeBodyPart(); // Set the data handler to the attachment messageBodyPart.setDataHandler(handler); if (attachmentFilename.toLowerCase().startsWith("cid:")) { // add a Content-ID header to the attachment // must use angle brackets according to RFC: http://www.ietf.org/rfc/rfc2392.txt messageBodyPart.addHeader("Content-ID", "<" + attachmentFilename.substring(4) + ">"); // Set the filename without the cid messageBodyPart.setFileName(attachmentFilename.substring(4)); } else { // Set the filename messageBodyPart.setFileName(attachmentFilename); } LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType()); if (contentTypeResolver != null) { String contentType = contentTypeResolver.resolveContentType(attachmentFilename); LOG.trace("Attachment #" + i + ": Using content type resolver: " + contentTypeResolver + " resolved content type as: " + contentType); if (contentType != null) { String value = contentType + "; name=" + attachmentFilename; messageBodyPart.setHeader("Content-Type", value); LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType()); } } // Set Disposition messageBodyPart.setDisposition(partDisposition); // Add part to multipart multipart.addBodyPart(messageBodyPart); } else { LOG.trace("shouldAddAttachment: false"); } } else { LOG.warn("Cannot add attachment: " + attachmentFilename + " as DataHandler is null"); } i++; } LOG.trace("Adding attachments +++ done +++"); }
From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java
public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException { log.trace("marshal(ShsMessage, OutputStream)"); MimeMultipart multipart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); try {/*from ww w. j a va 2s .c o m*/ ShsLabel label = shsMessage.getLabel(); if (label == null) { throw new IllegalMessageStructureException("label not found in shs message"); } Content content = label.getContent(); if (content == null) { throw new IllegalMessageStructureException("label/content not found in shs label"); } else { // we will update this according to our data parts below. content.getDataOrCompound().clear(); String contentId = content.getContentId(); content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID))); } List<DataPart> dataParts = shsMessage.getDataParts(); if (dataParts.isEmpty()) { throw new IllegalMessageStructureException("dataparts not found in message"); } for (DataPart dp : dataParts) { Data data = new Data(); data.setDatapartType(dp.getDataPartType()); data.setFilename(dp.getFileName()); if (dp.getContentLength() != null && dp.getContentLength() > 0) data.setNoOfBytes("" + dp.getContentLength()); content.getDataOrCompound().add(data); } bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1"); bodyPart.setHeader("Content-Transfer-Encoding", "binary"); multipart.addBodyPart(bodyPart); for (DataPart dataPart : dataParts) { bodyPart = new MimeBodyPart(); bodyPart.setDisposition(Part.ATTACHMENT); if (StringUtils.isNotBlank(dataPart.getFileName())) { bodyPart.setFileName(dataPart.getFileName()); } bodyPart.setDataHandler(dataPart.getDataHandler()); if (dataPart.getTransferEncoding() != null) { bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase()); } multipart.addBodyPart(bodyPart); } MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject("SHS Message"); mimeMessage.addHeader("Content-Transfer-Encoding", "binary"); mimeMessage.setContent(multipart); mimeMessage.saveChanges(); String ignoreList[] = { "Message-ID" }; mimeMessage.writeTo(outputStream, ignoreList); outputStream.flush(); } catch (Exception e) { if (e instanceof IllegalMessageStructureException) { throw (IllegalMessageStructureException) e; } throw new IllegalMessageStructureException(e); } }