List of usage examples for javax.mail BodyPart setContent
public void setContent(Object obj, String type) throws MessagingException;
From source file:com.tdclighthouse.commons.mail.util.MailClient.java
public void sendMail(String from, String[] to, Mail mail) throws MessagingException, AddressException { // a brief validation if ((from == null) || "".equals(from) || (to.length == 0) || (mail == null)) { throw new IllegalArgumentException(); }//from www .ja va 2 s . c om Session session = getSession(); // Define a new mail message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (int i = 0; i < to.length; i++) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); } message.setSubject(mail.getSubject(), "utf-8"); // use a MimeMultipart as we need to handle the file attachments Multipart multipart = new MimeMultipart("alternative"); if ((mail.getMessageBody() != null) && !"".equals(mail.getMessageBody())) { // add the message body to the mime message BodyPart textPart = new MimeBodyPart(); textPart.setContent(mail.getMessageBody(), "text/plain; charset=utf-8"); // sets type to "text/plain" multipart.addBodyPart(textPart); } if (mail.getHtmlBody() != null) { BodyPart pixPart = new MimeBodyPart(); pixPart.setContent(mail.getHtmlBody(), "text/html; charset=utf-8"); multipart.addBodyPart(pixPart); } // add any file attachments to the message addAtachments(mail.getAttachments(), multipart); // Put all message parts in the message message.setContent(multipart); // Send the message Transport.send(message); }
From source file:fr.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java
public void prepare(MimeMessage message) throws Exception { // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369 if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); }/* w w w . jav a2 s . c o m*/ if (getFrom() != null) { List<InternetAddress> toAddress = new ArrayList<InternetAddress>(); toAddress.add(new InternetAddress(getFrom(), getFromName())); message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()])); } if (getTo() != null) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo())); } if (getCc() != null) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc())); } if (getSubject() != null) { message.setSubject(getSubject()); } MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative message.setContent(mimeMultipart); if (getPlainTextContent() != null) { BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(getPlainTextContent(), "text/plain"); mimeMultipart.addBodyPart(textBodyPart); } if (getHtmlContent() != null) { BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(getHtmlContent(), "text/html"); mimeMultipart.addBodyPart(htmlBodyPart); } }
From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java
private void sendMessage(final String content) { try {/*from w w w . j av a 2 s. co m*/ MimeMessage msg = new MimeMessage(sessionProvider.get()); msg.setSubject("jFunk E-mail Report"); msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get()); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=UTF-8"); MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif"))); messageBodyPart.setHeader("Content-ID", "<check>"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif"))); messageBodyPart.setHeader("Content-ID", "<error>"); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); smtpClientProvider.get().send(msg); int anzahlRecipients = msg.getAllRecipients().length; log.info( "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get()); } catch (MessagingException e) { log.error("Error while creating report e-mail", e); } catch (MailException e) { log.error("Error while sending report e-mail", e); } }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private MimeMessage prepareHTMLMimeMessage(InternetAddress internetAddressFrom, String subject, String htmlBody, List<LabelValueBean> attachments) throws Exception { MimeMessage msg = new MimeMessage(session); msg.setFrom(internetAddressFrom);//from ww w . ja v a 2 s . c o m msg.setHeader(XMAILER, xmailer); msg.setSubject(subject.trim(), mailEncoding); msg.setSentDate(new Date()); MimeMultipart mimeMultipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); //Euro sign finally, shown correctly messageBodyPart.setContent(htmlBody, "text/html;charset=" + mailEncoding); mimeMultipart.addBodyPart(messageBodyPart); if (attachments != null && !attachments.isEmpty()) { LOGGER.debug("Use attachments: " + attachments.size()); includeAttachments(mimeMultipart, attachments); } msg.setContent(mimeMultipart); return msg; }
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); }//from www . j a v a 2 s . c o m }; 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:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java
private void addBody(MimeMessage msg) throws MessagingException { if (body != null) { Multipart multipart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(body, contentType()); multipart.addBodyPart(bodyPart); msg.setContent(multipart);/*from w w w . j a va 2 s . c o m*/ } }
From source file:mitm.common.mail.MailUtilsTest.java
@Test public void testUnknownContentTypeMultipartAddPart() throws IOException, MessagingException { MimeMessage message = loadMessage("unknown-content-type-multipart.eml"); MimeMultipart multipart = (MimeMultipart) message.getContent(); BodyPart newPart = new MimeBodyPart(); newPart.setContent("new part", "text/plain"); multipart.addBodyPart(newPart);/*from ww w . jav a 2 s . c o m*/ message.saveChanges(); MailUtils.validateMessage(message); File file = new File("test/tmp/testunknowncontenttypemultipartaddpart.eml"); MailUtils.writeMessage(message, file); }
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"); }//from www .j av a2s. c o m 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 av a2s . c o 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:org.jresponder.message.MessageRefImpl.java
/** * Render a message in the context of a particular subscriber * and subscription.//w ww. j a v a 2 s . c o m */ @Override public boolean populateMessage(MimeMessage aMimeMessage, SendConfig aSendConfig, Subscriber aSubscriber, Subscription aSubscription) { try { // prepare context Map<String, Object> myRenderContext = new HashMap<String, Object>(); myRenderContext.put("subscriber", aSubscriber); myRenderContext.put("subscription", aSubscription); myRenderContext.put("config", aSendConfig); myRenderContext.put("message", this); // render the whole file String myRenderedFileContents = TextRenderUtil.getInstance().render(fileContents, myRenderContext); // now parse again with Jsoup Document myDocument = Jsoup.parse(myRenderedFileContents); String myHtmlBody = ""; String myTextBody = ""; // html body Elements myBodyElements = myDocument.select("#htmlbody"); if (!myBodyElements.isEmpty()) { myHtmlBody = myBodyElements.html(); } // text body Elements myJrTextBodyElements = myDocument.select("#textbody"); if (!myJrTextBodyElements.isEmpty()) { myTextBody = TextUtil.getInstance().getWholeText(myJrTextBodyElements.first()); } // now build the actual message MimeMessage myMimeMessage = aMimeMessage; // wrap it in a MimeMessageHelper - since some things are easier with that MimeMessageHelper myMimeMessageHelper = new MimeMessageHelper(myMimeMessage); // set headers // subject myMimeMessageHelper.setSubject(TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_SUBJECT.toString()), myRenderContext)); // TODO: implement DKIM, figure out subetha String mySenderEmailPattern = aSendConfig.getSenderEmailPattern(); String mySenderEmail = TextRenderUtil.getInstance().render(mySenderEmailPattern, myRenderContext); myMimeMessage.setSender(new InternetAddress(mySenderEmail)); myMimeMessageHelper.setTo(aSubscriber.getEmail()); // from myMimeMessageHelper.setFrom( TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_FROM_EMAIL.toString()), myRenderContext), TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_FROM_NAME.toString()), myRenderContext)); // see how to set body // if we have both text and html, then do multipart if (myTextBody.trim().length() > 0 && myHtmlBody.trim().length() > 0) { // create wrapper multipart/alternative part MimeMultipart ma = new MimeMultipart("alternative"); myMimeMessage.setContent(ma); // create the plain text BodyPart plainText = new MimeBodyPart(); plainText.setText(myTextBody); ma.addBodyPart(plainText); // create the html part BodyPart html = new MimeBodyPart(); html.setContent(myHtmlBody, "text/html"); ma.addBodyPart(html); } // if only HTML, then just use that else if (myHtmlBody.trim().length() > 0) { myMimeMessageHelper.setText(myHtmlBody, true); } // if only text, then just use that else if (myTextBody.trim().length() > 0) { myMimeMessageHelper.setText(myTextBody, false); } // if neither text nor HTML, then the message is being skipped, // so we just return null else { return false; } return true; } catch (MessagingException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }