List of usage examples for javax.mail BodyPart setDataHandler
public void setDataHandler(DataHandler dh) throws MessagingException;
From source file:com.photon.phresco.util.Utility.java
public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body, String username, String password, String host, String screen, String build) throws PhrescoException { List<String> lists = Arrays.asList(toAddr); if (fromAddr == null) { fromAddr = "phresco.do.not.reply@gmail.com"; username = "phresco.do.not.reply@gmail.com"; password = "phresco123"; }//from w w w . j a v a 2s . com Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password)); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddr)); List<Address> emailsList = getEmailsList(lists); Address[] dsf = new Address[emailsList.size()]; message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf)); message.setSubject(subject); DataSource source = new FileDataSource(body); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName("Error.txt"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); MimeBodyPart messageBodyPart2 = new MimeBodyPart(); DataSource source2 = new FileDataSource(screen); messageBodyPart2.setDataHandler(new DataHandler(source2)); messageBodyPart2.setFileName("Error.jpg"); multipart.addBodyPart(messageBodyPart2); MimeBodyPart mainPart = new MimeBodyPart(); String content = "<b>Phresco framework error report<br><br>User Name: " + user + "<br> Email Address: " + fromAddr + "<br>Build No: " + build; mainPart.setContent(content, "text/html"); multipart.addBodyPart(mainPart); message.setContent(multipart); Transport.send(message); } catch (MessagingException e) { throw new PhrescoException(e); } }
From source file:sk.lazyman.gizmo.web.app.PageEmail.java
private Multipart createHtmlPart(String html) throws IOException, MessagingException { Multipart multipart = new MimeMultipart("related"); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setDisposition(MimeMessage.INLINE); DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(html, "text/html; charset=utf-8")); bodyPart.setDataHandler(dataHandler); multipart.addBodyPart(bodyPart);/* w w w. j a v a 2 s . com*/ return multipart; }
From source file:ste.xtest.mail.BugFreeFileTransport.java
@Test public void send_multipart_message() throws Exception { Session session = Session.getInstance(config); Message message = new MimeMessage(Session.getInstance(config)); message.setFrom(new InternetAddress("from@domain.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@domain.com")); message.setSubject("the subject"); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<H1>hello world</H1><img src=\"cid:image\">"; messageBodyPart.setContent(htmlText, "text/html"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource("src/test/resources/images/6096.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart);/*from ww w . j a v a 2 s .c o m*/ session.getTransport().sendMessage(message, message.getAllRecipients()); then(FileUtils.readFileToString(new File(TMP.getRoot(), "message"))).contains("From: from@domain.com\r") .contains("To: to@domain.com\r").contains("Subject: the subject\r").contains("hello world") .contains("Content-ID: <image>"); }
From source file:ee.cyber.licensing.service.MailService.java
public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId) throws MessagingException, IOException, SQLException { License license = licenseRepository.findById(licenseId); List<Contact> contacts = contactRepository.findAll(license.getCustomer()); List<String> receivers = getReceivers(mailbody, contacts); logger.info("1st ===> setup Mail Server Properties"); Properties mailServerProperties = getProperties(); final String email = mailServerProperties.getProperty("fromEmail"); final String password = mailServerProperties.getProperty("password"); final String host = mailServerProperties.getProperty("mail.smtp.host"); logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument"); Authenticator authentication = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(email, password); }// ww w. j av a2s. c om }; logger.info("Mail Server Properties have been setup successfully"); logger.info("3rd ===> get Mail Session.."); Session getMailSession = Session.getInstance(mailServerProperties, authentication); logger.info("4th ===> generateAndSendEmail() starts"); MimeMessage mailMessage = new MimeMessage(getMailSession); mailMessage.addHeader("Content-type", "text/html; charset=UTF-8"); mailMessage.addHeader("format", "flowed"); mailMessage.addHeader("Content-Transfer-Encoding", "8bit"); mailMessage.setFrom(new InternetAddress(email, "License dude")); //mailMessage.setReplyTo(InternetAddress.parse(email, false)); mailMessage.setSubject(mailbody.getSubject()); //String emailBody = body + "<br><br> Regards, <br>Cybernetica team"; mailMessage.setSentDate(new Date()); for (String receiver : receivers) { mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); } if (fileId != 0) { MailAttachment file = fileRepository.findById(fileId); if (file != null) { String fileName = file.getFileName(); byte[] fileData = file.getData_b(); if (fileName != null) { // Create a multipart message for attachment Multipart multipart = new MimeMultipart(); // Body part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(mailbody.getBody(), "text/html"); multipart.addBodyPart(messageBodyPart); //Attachment part messageBodyPart = new MimeBodyPart(); ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); mailMessage.setContent(multipart); } } } else { mailMessage.setContent(mailbody.getBody(), "text/html"); } logger.info("5th ===> Get Session"); sendMail(email, password, host, getMailSession, mailMessage); }
From source file:sk.lazyman.gizmo.web.app.PageEmail.java
private Message buildMail(Session session) throws MessagingException, IOException { String subject = createSubject(); Message mimeMessage = createMimeMessage(session, subject); mimeMessage.setDisposition(MimeMessage.INLINE); Multipart mp = new MimeMultipart("alternative"); MimeBodyPart textBp = new MimeBodyPart(); textBp.setDisposition(MimeMessage.INLINE); textBp.setContent("Please use mail client with HTML support.", "text/plain; charset=utf-8"); mp.addBodyPart(textBp);// w w w. ja v a 2 s . co m Multipart commentMultipart = null; EmailDto dto = model.getObject(); if (StringUtils.isNotEmpty(dto.getBody())) { BodyPart bodyPart = new MimeBodyPart(); bodyPart.setDisposition(MimeMessage.INLINE); DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(dto.getBody(), "text/plain; charset=utf-8")); bodyPart.setDataHandler(dataHandler); commentMultipart = new MimeMultipart("mixed"); commentMultipart.addBodyPart(bodyPart); } String html = createHtml(); Multipart htmlMp = createHtmlPart(html); BodyPart htmlBp = new MimeBodyPart(); htmlBp.setDisposition(BodyPart.INLINE); htmlBp.setContent(htmlMp); if (commentMultipart == null) { mp.addBodyPart(htmlBp); } else { commentMultipart.addBodyPart(htmlBp); BodyPart all = new MimeBodyPart(); all.setDisposition(BodyPart.INLINE); all.setContent(commentMultipart); mp.addBodyPart(all); } mimeMessage.setContent(mp); return mimeMessage; }
From source file:org.ambraproject.wombat.service.FreemarkerMailServiceImpl.java
private BodyPart createBodyPart(ContentType contentType, Template htmlTemplate, Model context) throws IOException, MessagingException { BodyPart htmlPage = new MimeBodyPart(); String encoding = getConfiguration().getDefaultEncoding(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(0x100); Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream, encoding)); htmlTemplate.setOutputEncoding(encoding); htmlTemplate.setEncoding(encoding);//from www. ja va2 s . c o m try { htmlTemplate.process(context, writer); } catch (TemplateException e) { throw new MailPreparationException("Can't generate " + contentType.getMimeType() + " subscription mail", e); } htmlPage.setDataHandler(createBodyPartDataHandler(outputStream.toByteArray(), contentType.toString() + "; charset=" + getConfiguration().getDefaultEncoding())); return htmlPage; }
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 w w . j a v a 2s . c o m 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: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;//from w ww. j a v a 2s . c o m // 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.codice.alliance.core.email.impl.EmailSenderImpl.java
/** sendEmail method sends email after receiving input parameters */ @Override/*from w w w .j a v a 2s. c o m*/ public void sendEmail(String fromEmail, String toEmail, String subject, String body, List<Pair<String, InputStream>> attachments) throws IOException { notNull(fromEmail, "fromEmail must be non-null"); notNull(toEmail, "toEmail must be non-null"); notNull(subject, "subject must be non-null"); notNull(body, "body must be non-null"); notNull(attachments, "attachments must be non-null"); if (StringUtils.isBlank(mailHost)) { throw new IOException("the mail server hostname has not been configured"); } List<File> tempFiles = new LinkedList<>(); try { InternetAddress emailAddr = new InternetAddress(toEmail); emailAddr.validate(); Properties properties = createSessionProperties(); Session session = Session.getDefaultInstance(properties); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(fromEmail)); mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr); mimeMessage.setSubject(subject); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Holder<Long> bytesWritten = new Holder<>(0L); for (Pair<String, InputStream> attachment : attachments) { messageBodyPart = new MimeBodyPart(); File file = File.createTempFile("email-sender-", ".dat"); tempFiles.add(file); copyDataToTempFile(file, attachment.getValue(), bytesWritten); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file))); messageBodyPart.setFileName(attachment.getKey()); multipart.addBodyPart(messageBodyPart); } mimeMessage.setContent(multipart); send(mimeMessage); LOGGER.debug("Email sent to " + toEmail); } catch (AddressException e) { throw new IOException("invalid email address: email=" + toEmail, e); } catch (MessagingException e) { throw new IOException("message error occurred on send", e); } finally { tempFiles.forEach(file -> { if (!file.delete()) { LOGGER.debug("unable to delete tmp file: path={}", file); } }); } }
From source file:net.sf.jclal.util.mail.SenderEmail.java
/** * Send the email with the indicated parameters * * @param subject The subject/*from w w w . j a va 2s . c o m*/ * @param content The content * @param reportFile The reportFile to send */ public void sendEmail(String subject, String content, File reportFile) { // Get system properties Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); if (!user.isEmpty() && !pass.isEmpty()) { properties.setProperty("mail.user", user); properties.setProperty("mail.password", pass); } // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipients(Message.RecipientType.TO, toRecipients.toString()); // Set Subject: header field message.setSubject(subject); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText(content); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); if (attachReporFile) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile))); messageBodyPart.setFileName(reportFile.getName()); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e); } }