List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java
protected void sendEmail(Email email, List<Email> successfulEmails) { try {//from ww w. j a v a2 s. co m if (logger.isDebugEnabled()) { logger.debug("Attempting to send " + email.getId() + " " + email.getSubject()); if (email.getTo() != null) { logger.debug("To: " + Arrays.toString(email.getTo().toArray())); } else { logger.debug("To is NULL"); } if (email.getTo() != null) { logger.debug("CC: " + Arrays.toString(email.getCc().toArray())); } else { logger.debug("CC is NULL"); } if (email.getTo() != null) { logger.debug("BCC: " + Arrays.toString(email.getBcc().toArray())); } else { logger.debug("BCC is NULL"); } if (email.getTo() != null) { logger.debug("FROM: " + email.getFrom()); } else { logger.debug("FROM is NULL"); } if (email.getAttachments() != null) { logger.debug("Attachments: " + Arrays.toString(email.getAttachments().toArray())); for (Attachments attachment : email.getAttachments()) { logger.debug("Attachment: " + attachment.getName()); } } else { logger.debug("No attachments"); } } //Send email if (StringUtils.isBlank(email.getSubject()) || StringUtils.isBlank(email.getFrom())) { logger.warn(new StringBuilder("Invalid email without either from or a subject, thus ignoring it ") .append(email.getId()).toString()); return; } MimeMessage message = new MimeMessage(session); message.setSubject(email.getSubject()); message.setFrom(new InternetAddress(email.getFrom())); addRecipients(message, Message.RecipientType.TO, email.getTo()); addRecipients(message, Message.RecipientType.CC, email.getCc()); addRecipients(message, Message.RecipientType.BCC, email.getBcc()); if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody()) && email.getMessage().getMsgType().equals(MsgType.PLAIN) && (email.getAttachments() == null || email.getAttachments().isEmpty())) { message.setText(email.getMessage().getMsgBody()); } else { Multipart multipart = new MimeMultipart(); if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())) { MimeBodyPart bodyPart = new MimeBodyPart(); switch (email.getMessage().getMsgType()) { case HTML: bodyPart.setContent(email.getMessage().getMsgBody(), "html"); break; case PLAIN: default: bodyPart.setText(email.getMessage().getMsgBody()); } multipart.addBodyPart(bodyPart); } if (email.getAttachments() != null && !email.getAttachments().isEmpty()) { for (Attachments attachment : email.getAttachments()) { addAttachment(multipart, attachment); } } message.setContent(multipart); } Transport.send(message); if (logger.isDebugEnabled()) { logger.debug("Sent " + email.getId()); } //Update status email.setMailStatus(Email.MailStatus.SENT); successfulEmails.add(email); if (logger.isDebugEnabled()) { logger.debug("Set new mail status and add to successful queue " + email.getSubject()); } } catch (Exception ex) { logger.warn( new StringBuilder("Error sending email with subject ").append(email.getSubject()).toString(), ex); } }
From source file:org.jresponder.message.MessageRefImpl.java
/** * Render a message in the context of a particular subscriber * and subscription.// w w w.ja 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); } }
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 ww .j a va 2 s.com 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.fogbowcloud.manager.core.plugins.util.CloudInitUserDataBuilder.java
/** * Add given file <code>in</code> to the cloud-init mime message. * //from w w w . jav a2 s . com * @param fileType * @param in * file to add as readable * @return the builder * @throws IllegalArgumentException * the given <code>fileType</code> was already added to this * cloud-init mime message. */ public CloudInitUserDataBuilder addFile(FileType fileType, Readable in) throws IllegalArgumentException { Preconditions.checkNotNull(fileType, "'fileType' can NOT be null"); Preconditions.checkNotNull(in, "'in' can NOT be null"); //Preconditions.checkArgument(!alreadyAddedFileTypes.contains(fileType), "%s as already been added", fileType); alreadyAddedFileTypes.add(fileType); try { StringWriter sw = new StringWriter(); CharStreams.copy(in, sw); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(sw.toString(), charset.name(), fileType.getMimeTextSubType()); mimeBodyPart.setFileName((userDataCounter++) + fileType.getFileName()); userDataMultipart.addBodyPart(mimeBodyPart); } catch (IOException e) { throw Throwables.propagate(e); } catch (MessagingException e) { throw Throwables.propagate(e); } return this; }
From source file:fr.xebia.cloud.cloudinit.CloudInitUserDataBuilder.java
/** * Add given file <code>in</code> to the cloud-init mime message. * /*from w ww. j a v a2s . co m*/ * @param fileType * @param in * file to add as readable * @return the builder * @throws IllegalArgumentException * the given <code>fileType</code> was already added to this * cloud-init mime message. */ @Nonnull public CloudInitUserDataBuilder addFile(@Nonnull FileType fileType, @Nonnull Readable in) throws IllegalArgumentException { Preconditions.checkNotNull(fileType, "'fileType' can NOT be null"); Preconditions.checkNotNull(in, "'in' can NOT be null"); Preconditions.checkArgument(!alreadyAddedFileTypes.contains(fileType), "%s as already been added", fileType); alreadyAddedFileTypes.add(fileType); try { StringWriter sw = new StringWriter(); CharStreams.copy(in, sw); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(sw.toString(), charset.name(), fileType.getMimeTextSubType()); mimeBodyPart.setFileName(fileType.getFileName()); userDataMultipart.addBodyPart(mimeBodyPart); } catch (IOException e) { throw Throwables.propagate(e); } catch (MessagingException e) { throw Throwables.propagate(e); } return this; }
From source file:org.apache.mailet.base.test.MimeMessageBuilder.java
public MimeMessage build() throws MessagingException { Preconditions.checkState(!(text.isPresent() && content.isPresent()), "Can not get at the same time a text and a content"); MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties())); if (text.isPresent()) { BodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(text.get());//from w w w . jav a2s . co m mimeMessage.setContent(bodyPart, "text/plain"); } if (content.isPresent()) { mimeMessage.setContent(content.get()); } if (sender.isPresent()) { mimeMessage.setSender(sender.get()); } if (from.isPresent()) { mimeMessage.setFrom(from.get()); } if (subject.isPresent()) { mimeMessage.setSubject(subject.get()); } List<InternetAddress> toAddresses = to.build(); if (!toAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses.toArray(new InternetAddress[toAddresses.size()])); } List<InternetAddress> ccAddresses = cc.build(); if (!ccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[ccAddresses.size()])); } List<InternetAddress> bccAddresses = bcc.build(); if (!bccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddresses.toArray(new InternetAddress[bccAddresses.size()])); } List<Header> headerList = headers.build(); for (Header header : headerList) { mimeMessage.addHeader(header.name, header.value); } mimeMessage.saveChanges(); return mimeMessage; }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { Map parametersMap;/*w w w .j ava 2s. co m*/ String contentType; String fileExtension; IDataStore emailDispatchDataStore; String nameSuffix; String descriptionSuffix; String containedFileName; String zipFileName; boolean reportNameInSubject; logger.debug("IN"); try { parametersMap = dispatchContext.getParametersMap(); contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore(); nameSuffix = dispatchContext.getNameSuffix(); descriptionSuffix = dispatchContext.getDescriptionSuffix(); containedFileName = dispatchContext.getContainedFileName() != null && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName() : document.getName(); zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("") ? dispatchContext.getZipMailName() : document.getName(); reportNameInSubject = dispatchContext.isReportNameInSubject(); String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); int smptPort = 25; if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); String mailSubj = dispatchContext.getMailSubj(); mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = dispatchContext.getMailTxt(); String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore); if (recipients == null || recipients.length == 0) { logger.error("No recipients found for email sending!!!"); return false; } //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } //session = Session.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type String subject = mailSubj; if (reportNameInSubject) { subject += " " + document.getName() + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt + "\n" + descriptionSuffix); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = null; //if zip requested if (dispatchContext.isZipMailDocument()) { mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension); } //else else { sds = new SchedulerDataSource(executionOutput, contentType, containedFileName + nameSuffix + fileExtension); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.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); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smptPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { //Use normal SMTP Transport.send(msg); } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:com.waveerp.sendMail.java
public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg, String strDestination, String strDestDesc, String strPath) throws Exception { String strResult = "OK"; // Call the registry management system registrySystem rs = new registrySystem(); // Call the encryption management system desEncryption de = new desEncryption(); de.Encrypter("", ""); String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST"); String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT"); final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER"); String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD"); //Decrypt the encrypted password. final String strPass01 = de.decrypt(strPass); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", strHost); props.put("mail.smtp.port", strPort); props.put("mail.user", strUser); props.put("mail.password", strPass01); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPass01); }/*from w w w.j a va 2 s . c om*/ }; Session session = Session.getInstance(props, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(strSource)); //InternetAddress[] toAddresses = { new InternetAddress(strDestination) }; msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination)); msg.setSubject(strSubject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(strMsg, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments //if (attachFiles != null && attachFiles.length > 0) { // for (String filePath : attachFiles) { // MimeBodyPart attachPart = new MimeBodyPart(); // // try { // attachPart.attachFile(filePath); // } catch (IOException ex) { // ex.printStackTrace(); // } // // multipart.addBodyPart(attachPart); // } //} String fna; String fnb; URL fileUrl; fileUrl = null; fileUrl = this.getClass().getResource("sendMail.class"); fna = fileUrl.getPath(); fna = fna.substring(0, fna.indexOf("WEB-INF")); //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath ); fnb = URLDecoder.decode(fna + strPath); MimeBodyPart attachPart = new MimeBodyPart(); try { attachPart.attachFile(fnb); } catch (IOException ex) { //ex.printStackTrace(); strResult = ex.getMessage(); } multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); return strResult; }
From source file:no.kantega.publishing.modules.mailsender.MailSender.java
/** * Helper method to create a MimeBodyPart from a string. * * @param content The string to insert into the MimeBodyPart. * @return The resulting MimeBodyPart.//from w w w. j a v a2 s . c o m * @throws SystemException if the MimeBodyPart can't be created. */ public static MimeBodyPart createMimeBodyPartFromStringMessage(String content) throws SystemException { try { MimeBodyPart bp = new MimeBodyPart(); if (content.toLowerCase().contains("<html>")) { log.debug("Set content as text/html"); bp.setContent(content, "text/html; charset=iso-8859-1"); } else { log.debug("Set content as text/plain"); bp.setText(content, "ISO-8859-1"); bp.setHeader("Content-Transfer-Encoding", "quoted-printable"); } return bp; } catch (MessagingException e) { throw new SystemException("Feil ved generering av MimeBodyPart fra string", e); } }
From source file:gmailclientfx.core.GmailClient.java
public static void sendMessage(String to, String subject, String body, List<String> attachments) throws Exception { // authenticate with gmail smtp server SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true); // kreiraj MimeMessage objekt MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession()); // dodaj headere msg.addHeader("Content-type", "text/HTML; charset=UTF-8"); msg.addHeader("format", "flowed"); msg.addHeader("Content-Transfer-Encoding", "8bit"); msg.setFrom(new InternetAddress(EMAIL)); msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to)); msg.setSubject(subject, "UTF-8"); msg.setReplyTo(InternetAddress.parse(EMAIL, false)); // tijelo poruke BodyPart msgBodyPart = new MimeBodyPart(); msgBodyPart.setText(body);/*from w w w . j a va 2 s .c o m*/ Multipart multipart = new MimeMultipart(); multipart.addBodyPart(msgBodyPart); msg.setContent(multipart); // dodaj privitke if (attachments.size() > 0) { for (String attachment : attachments) { msgBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); msgBodyPart.setDataHandler(new DataHandler(source)); msgBodyPart.setFileName(source.getName()); multipart.addBodyPart(msgBodyPart); } msg.setContent(multipart); } smtpTransport.sendMessage(msg, InternetAddress.parse(to)); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Poruka poslana!"); alert.setHeaderText(null); alert.setContentText("Email uspjeno poslan!"); alert.showAndWait(); }