List of usage examples for javax.mail.internet MimeMessage setContent
@Override public void setContent(Multipart mp) throws MessagingException
From source file:com.flexoodb.common.FlexUtils.java
/** * use this method to obtain a mimemessage with the file wrapped in it. * * @param filename filename of the file. * @param data the file in bytes./*from w ww .j av a 2s. c o m*/ * @return a byte array of the mimemessage. */ static public byte[] wrapInMimeMessage(String filename, byte[] data) throws Exception { MimeMessage mimemessage = new MimeMessage(javax.mail.Session.getDefaultInstance(new Properties(), null)); BodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); DataSource source = new ByteArrayDataSource(data, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); mimemessage.setContent(multipart); mimemessage.saveChanges(); // finally pipe to an array so we can conver to string ByteArrayOutputStream bos = new ByteArrayOutputStream(); mimemessage.writeTo(bos); return bos.toString().getBytes(); }
From source file:org.etudes.component.app.jforum.JForumEmailServiceImpl.java
/** * Sends email with attachments/*w w w. j ava 2 s. c o m*/ * * @param from * The address this message is to be listed as coming from. * @param to * The address(es) this message should be sent to. * @param subject * The subject of this message. * @param content * The body of the message. * @param headerToStr * If specified, this is placed into the message header, but "to" is used for the recipients. * @param replyTo * If specified, this is the reply to header address(es). * @param additionalHeaders * Additional email headers to send (List of String). For example, content type or forwarded headers (may be null) * @param messageAttachments * Message attachments */ protected void sendMailWithAttachments(InternetAddress from, InternetAddress[] to, String subject, String content, InternetAddress[] headerTo, InternetAddress[] replyTo, List<String> additionalHeaders, List<EmailAttachment> emailAttachments) { if (testMode) { testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders, emailAttachments); return; } if (smtp == null || smtp.trim().length() == 0) { if (logger.isWarnEnabled()) { logger.warn("sendMailWithAttachments: smtp not set"); } return; } if (from == null) { if (logger.isWarnEnabled()) { logger.warn("sendMail: from is needed to send email"); } return; } if (to == null) { if (logger.isWarnEnabled()) { logger.warn("sendMail: to is needed to send email"); } return; } if (content == null) { if (logger.isWarnEnabled()) { logger.warn("sendMail: content is needed to send email"); } return; } if (emailAttachments == null || emailAttachments.size() == 0) { if (logger.isWarnEnabled()) { logger.warn("sendMail: emailAttachments are needed to send email with attachments"); } return; } try { if (session == null) { if (logger.isWarnEnabled()) { logger.warn("mail session is null"); } return; } MimeMessage message = new MimeMessage(session); // default charset String charset = "UTF-8"; message.setSentDate(new Date()); message.setFrom(from); message.setSubject(subject, charset); MimeBodyPart messageBodyPart = new MimeBodyPart(); // Content-Type: text/plain; text/html; String contentType = null, contentTypeValue = null; if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith("content-type:")) { contentType = header; contentTypeValue = contentType.substring( contentType.indexOf("content-type:") + "content-type:".length(), contentType.length()); break; } } } // message String messagetype = ""; if ((contentTypeValue != null) && (contentTypeValue.trim().equalsIgnoreCase("text/html"))) { messagetype = "text/html; charset=" + charset; messageBodyPart.setContent(content, messagetype); } else { messagetype = "text/plain; charset=" + charset; messageBodyPart.setContent(content, messagetype); } //messageBodyPart.setContent(content, "text/html; charset="+ charset); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); String jforumAttachmentStoreDir = serverConfigurationService() .getString(JForumAttachmentService.ATTACHMENTS_STORE_DIR); if (jforumAttachmentStoreDir == null || jforumAttachmentStoreDir.trim().length() == 0) { if (logger.isWarnEnabled()) { logger.warn("JForum attachments directory (" + JForumAttachmentService.ATTACHMENTS_STORE_DIR + ") property is not set in sakai.properties "); } } else { // attachments for (EmailAttachment emailAttachment : emailAttachments) { String filePath = jforumAttachmentStoreDir + "/" + emailAttachment.getPhysicalFileName(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); try { messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(emailAttachment.getRealFileName()); multipart.addBodyPart(messageBodyPart); } catch (MessagingException e) { if (logger.isWarnEnabled()) { logger.warn("Error while attaching attachments: " + e, e); } } } } message.setContent(multipart); Transport.send(message, to); } catch (MessagingException e) { if (logger.isWarnEnabled()) { logger.warn("sendMail: Error in sending email: " + e, e); } } }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail from a Mail object// w w w .j av a 2 s. co m */ public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({})", mail); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (mail.getFrom() != null) { InternetAddress from = new InternetAddress(mail.getFrom()); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[mail.getTo().length]; int i = 0; for (String strTo : mail.getTo()) { to[i++] = new InternetAddress(strTo); } // Build a multiparted mail with HTML and text content for better SPAM behaviour MimeMultipart content = new MimeMultipart(); if (Mail.MIME_TEXT.equals(mail.getMimeType())) { // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } else if (Mail.MIME_HTML.equals(mail.getMimeType())) { // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(mail.getContent()); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html"); htmlPart.setHeader("Content-Type", "text/html"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); } else { log.warn("Email does not specify content MIME type"); // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } for (Document doc : mail.getAttachments()) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(doc.getPath()); try { is = OKMDocument.getInstance().getContent(token, doc.getPath(), false); File tmp = File.createTempFile("okm", ".tmp"); fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmp.getPath()); docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(docName); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(mail.getSubject(), "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java
@Override public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) { return new AbstractMailSendBuilder() { @Override//from w ww.ja v a 2 s . co m public void send(final String content) throws Exception { __sendExecPool.execute(new Runnable() { @Override public void run() { try { MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed()); // for (String _to : getTo()) { _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to)); } for (String _cc : getCc()) { _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc)); } for (String _bcc : getBcc()) { _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc)); } // if (getLevel() != null) { switch (getLevel()) { case LEVEL_HIGH: _message.setHeader("X-MSMail-Priority", "High"); _message.setHeader("X-Priority", "1"); break; case LEVEL_NORMAL: _message.setHeader("X-MSMail-Priority", "Normal"); _message.setHeader("X-Priority", "3"); break; case LEVEL_LOW: _message.setHeader("X-MSMail-Priority", "Low"); _message.setHeader("X-Priority", "5"); break; default: } } // String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8"); _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(), serverCfgMeta.getDisplayName(), _charset)); _message.setSubject(getSubject(), _charset); // Multipart _container = new MimeMultipart(); // MimeBodyPart _textBodyPart = new MimeBodyPart(); if (getMimeType() == null) { mimeType(IMailSender.MimeType.TEXT_PLAIN); } _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset); _container.addBodyPart(_textBodyPart); // ??<img src="cid:<CID_NAME>"> for (PairObject<String, File> _file : getAttachments()) { if (_file.getValue() != null) { MimeBodyPart _fileBodyPart = new MimeBodyPart(); FileDataSource _fileDS = new FileDataSource(_file.getValue()); _fileBodyPart.setDataHandler(new DataHandler(_fileDS)); if (_file.getKey() != null) { _fileBodyPart.setHeader("Content-ID", _file.getKey()); } _fileBodyPart.setFileName(_fileDS.getName()); _container.addBodyPart(_fileBodyPart); } } // ?? _message.setContent(_container); Transport.send(_message); } catch (Exception e) { throw new RuntimeException(RuntimeUtils.unwrapThrow(e)); } } }); } }; }
From source file:com.email.SendEmail.java
/** * Sends a single email and uses account based off of the section that the * email comes from after email is sent the attachments are gathered * together and collated into a single PDF file and a history entry is * created based off of that entry//from w w w .j a v a 2 s. com * * @param eml EmailOutModel */ public static void sendEmails(EmailOutModel eml) { SystemEmailModel account = null; String section = eml.getSection(); if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED") || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) { section = eml.getCaseType(); } //Get Account for (SystemEmailModel acc : Global.getSystemEmailParams()) { if (acc.getSection().equals(section)) { account = acc; break; } } //Account Exists? if (account != null) { //Case Location String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(eml) : FileService.getCaseFolderLocation(eml); //Attachment List boolean allFilesExists = true; List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId()); for (EmailOutAttachmentModel attach : attachmentList) { File attachment = new File(casePath + attach.getFileName()); boolean exists = attachment.exists(); if (exists == false) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("FileMissing"); item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } else { if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName())) || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) { if (!attachment.renameTo(attachment)) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("File In Use"); item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } } } } if (allFilesExists) { //Set up Initial Merge Utility PDFMergerUtility ut = new PDFMergerUtility(); //List ConversionPDFs To Delete Later List<String> tempPDFList = new ArrayList<>(); //create email message body Date emailSentTime = new Date(); String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime); //Add Email Body To PDF Merge try { ut.addSource(casePath + emailPDFname); tempPDFList.add(casePath + emailPDFname); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //Get parts String FromAddress = account.getEmailAddress(); String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";")); String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";")); String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";")); String emailSubject = eml.getSubject(); String emailBody = eml.getBody(); //Set Email Parts Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailOutProperties(account); Session session = Session.getInstance(properties, auth); MimeMessage smessage = new MimeMessage(session); Multipart multipart = new MimeMultipart(); //Add Parts to Email Message try { smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) }); for (String To : TOAddressess) { if (EmailValidator.getInstance().isValid(To)) { smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To)); } } for (String CC : CCAddressess) { if (EmailValidator.getInstance().isValid(CC)) { smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC)); } } for (String BCC : BCCAddressess) { if (EmailValidator.getInstance().isValid(BCC)) { smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC)); } } smessage.setSubject(emailSubject); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailBody, "text/plain"); multipart.addBodyPart(messageBodyPart); //get attachments for (EmailOutAttachmentModel attachment : attachmentList) { String fileName = attachment.getFileName(); String extension = FilenameUtils.getExtension(fileName); //Convert attachments to PDF //If Image if (FileService.isImageFormat(fileName)) { fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Word Doc } else if (extension.equals("docx") || extension.equals("doc")) { fileName = WordToPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Text File } else if ("txt".equals(extension)) { fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If PDF } else if (FilenameUtils.getExtension(fileName).equals("pdf")) { //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } } DataSource source = new FileDataSource(casePath + fileName); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } smessage.setContent(multipart); //Send Message if (Global.isOkToSendEmail()) { Transport.send(smessage); } else { Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject); } //DocumentFileName String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject()) .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf"; //Set Merge File Destination ut.setDestinationFileName(casePath + savedDoc); //Try to Merge try { ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); } catch (IOException ex) { ExceptionHandler.Handle(ex); } //Add emailBody Activity addEmailActivity(eml, savedDoc, emailSentTime); //Copy to related case folders if (section.equals("MED")) { List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml); if (relatedMedList.size() > 0) { for (RelatedCaseModel related : relatedMedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } else { //This is blanket and should grab all related cases. (UNTESTED outside of CMDS) List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml); if (relatedList.size() > 0) { for (EmailOutRelatedCaseModel related : relatedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationEmailOutRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } //Clean SQL entries EmailOut.deleteEmailEntry(eml.getId()); EmailOutAttachment.deleteAttachmentsForEmail(eml.getId()); EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId()); //Clean up temp PDFs for (String tempPDF : tempPDFList) { new File(tempPDF).delete(); } } catch (AddressException ex) { ExceptionHandler.Handle(ex); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:org.sakaiproject.tool.mailtool.Mailtool.java
public String processSendEmail() { /* EmailUser */ selected = m_recipientSelector.getSelectedUsers(); if (m_selectByTree) { selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers(); selectedGroupUsers = m_recipientSelector2.getSelectedUsers(); selectedSectionUsers = m_recipientSelector3.getSelectedUsers(); selected.addAll(selectedGroupAwareRoleUsers); selected.addAll(selectedGroupUsers); selected.addAll(selectedSectionUsers); }//w w w.j a v a2 s . co m // Put everyone in a set so the same person doesn't get multiple emails. Set emailusers = new TreeSet(); if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future for (Iterator i = getEmailGroups().iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); emailusers.addAll(group.getEmailusers()); } } if (isAllGroupSelected()) { for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("section")) { selected.addAll(group.getEmailusers()); } } } if (isAllSectionSelected()) { for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("group")) { selected.addAll(group.getEmailusers()); } } } if (isAllGroupAwareRoleSelected()) { for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("role_groupaware")) { selected.addAll(group.getEmailusers()); } } } emailusers = new TreeSet(selected); // convert List to Set (remove duplicates) m_subjectprefix = getSubjectPrefixFromConfig(); EmailUser curUser = getCurrentUser(); String fromEmail = ""; String fromDisplay = ""; if (curUser != null) { fromEmail = curUser.getEmail(); fromDisplay = curUser.getDisplayname(); } String fromString = fromDisplay + " <" + fromEmail + ">"; m_results = "Message sent to: <br>"; String subject = m_subject; //Should we append this to the archive? String emailarchive = "/mailarchive/channel/" + m_siteid + "/main"; if (m_archiveMessage && isEmailArchiveInSite()) { String attachment_info = "<br/>"; Attachment a = null; Iterator iter = attachedFiles.iterator(); int i = 0; while (iter.hasNext()) { a = (Attachment) iter.next(); attachment_info += "<br/>"; attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize() + " Bytes)"; i++; } this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info); } List headers = new ArrayList(); if (getTextFormat().equals("htmltext")) headers.add("content-type: text/html"); else headers.add("content-type: text/plain"); String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); //String smtp_port = ServerConfigurationService.getString("smtp.port"); try { Properties props = new Properties(); props.put("mail.smtp.host", smtp_server); //props.put("mail.smtp.port", smtp_port); Session s = Session.getInstance(props, null); MimeMessage message = new MimeMessage(s); InternetAddress from = new InternetAddress(fromString); message.setFrom(from); String reply = getReplyToSelected().trim().toLowerCase(); if (reply.equals("yes")) { // "reply to sender" is default. So do nothing } else if (reply.equals("no")) { String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">"; InternetAddress noreplyemail = new InternetAddress(noreply); message.setFrom(noreplyemail); } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) { // need input(email) validation InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) }; message.setReplyTo(replytoList); } message.setSubject(subject); String text = m_body; String attachmentdirectory = getUploadDirectory(); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message String messagetype = ""; if (getTextFormat().equals("htmltext")) { messagetype = "text/html"; } else { messagetype = "text/plain"; } messageBodyPart.setContent(text, messagetype); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment Attachment a = null; Iterator iter = attachedFiles.iterator(); while (iter.hasNext()) { a = (Attachment) iter.next(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource( attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename()); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(a.getFilename()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); //Send the emails String recipientsString = ""; for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") { EmailUser euser = (EmailUser) i.next(); String toEmail = euser.getEmail(); // u.getEmail(); String toDisplay = euser.getDisplayname(); // u.getDisplayName(); // if AllUsers are selected, do not add current user's email to recipients if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) { // don't add sender to recipients } else { recipientsString += toEmail; m_results += toDisplay + (i.hasNext() ? "<br/>" : ""); } // InternetAddress to[] = {new InternetAddress(toEmail) }; // Transport.send(message,to); } if (m_otheremails.trim().equals("") != true) { // // multiple email validation is needed here // String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ','); recipientsString += refinedOtherEmailAddresses; m_results += "<br/>" + refinedOtherEmailAddresses; // InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) }; // Transport.send(message, to); } if (m_sendmecopy) { message.addRecipients(Message.RecipientType.CC, fromEmail); // trying to solve SAK-7410 // recipientsString+=fromEmail; // InternetAddress to[] = {new InternetAddress(fromEmail) }; // Transport.send(message, to); } // message.addRecipients(Message.RecipientType.TO, recipientsString); message.addRecipients(Message.RecipientType.BCC, recipientsString); Transport.send(message); } catch (Exception e) { log.debug("Mailtool Exception while trying to send the email: " + e.getMessage()); } // Clear the Subject and Body of the Message m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix(); m_otheremails = ""; m_body = ""; num_files = 0; attachedFiles.clear(); m_recipientSelector = null; m_recipientSelector1 = null; m_recipientSelector2 = null; m_recipientSelector3 = null; setAllUsersSelected(false); setAllGroupSelected(false); setAllSectionSelected(false); // Display Users with Bad Emails if the option is turned on. boolean showBadEmails = getDisplayInvalidEmailAddr(); if (showBadEmails == true) { m_results += "<br/><br/>"; List /* String */ badnames = new ArrayList(); for (Iterator i = selected.iterator(); i.hasNext();) { EmailUser user = (EmailUser) i.next(); /* This check should maybe be some sort of regular expression */ if (user.getEmail().equals("")) { badnames.add(user.getDisplayname()); } } if (badnames.size() > 0) { m_results += "The following users do not have valid email addresses:<br/>"; for (Iterator i = badnames.iterator(); i.hasNext();) { String name = (String) i.next(); if (i.hasNext() == true) m_results += name + "/ "; else m_results += name; } } } return "results"; }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
@Override public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject, String body, List<File> attachments, MailerResult result) { try {/*from w w w . j a v a 2 s.co m*/ // see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection. // following doesn't work correctly, therefore add bounce-address in message already Address convertedFrom = getRawEmailFromAddress(from); MimeMessage msg = createMessage(convertedFrom); Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"), WebappHelper.getMailConfig("mailFromName")); msg.setFrom(viewableFrom); msg.setSubject(subject, "utf-8"); // reply to can only be an address without name (at least for postfix!), see FXOLAT-312 msg.setReplyTo(new Address[] { convertedFrom }); if (tos != null && tos.length > 0) { msg.addRecipients(RecipientType.TO, tos); } if (ccs != null && ccs.length > 0) { msg.addRecipients(RecipientType.CC, ccs); } if (bccs != null && bccs.length > 0) { msg.addRecipients(RecipientType.BCC, bccs); } if (attachments != null && !attachments.isEmpty()) { // with attachment use multipart message Multipart multipart = new MimeMultipart("mixed"); // 1) add body part if (StringHelper.isHtml(body)) { Multipart alternativePart = createMultipartAlternative(body); MimeBodyPart wrap = new MimeBodyPart(); wrap.setContent(alternativePart); multipart.addBodyPart(wrap); } else { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); } // 2) add attachments for (File attachmentFile : attachments) { // abort if attachment does not exist if (attachmentFile == null || !attachmentFile.exists()) { result.setReturnCode(MailerResult.ATTACHMENT_INVALID); logError("Tried to send mail wit attachment that does not exist::" + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null); return msg; } BodyPart filePart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFile); filePart.setDataHandler(new DataHandler(source)); filePart.setFileName(attachmentFile.getName()); multipart.addBodyPart(filePart); } // Put parts in message msg.setContent(multipart); } else { // without attachment everything is easy, just set as text if (StringHelper.isHtml(body)) { msg.setContent(createMultipartAlternative(body)); } else { msg.setText(body, "utf-8"); } } msg.setSentDate(new Date()); msg.saveChanges(); return msg; } catch (AddressException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } catch (MessagingException e) { result.setReturnCode(MailerResult.SEND_GENERAL_ERROR); logError("", e); return null; } catch (UnsupportedEncodingException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } }
From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java
public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) { // Retrieve SMTP server information String host = getSmtpHost();/* ww w. j a v a 2s .com*/ boolean isSmtpAuthentication = isSmtpAuthentication(); int smtpPort = getSmtpPort(); String smtpUser = getSmtpUser(); String smtpPwd = getSmtpPwd(); boolean isSmtpDebug = isSmtpDebug(); List<String> emailErrors = new ArrayList<String>(); if (emails.size() > 0) { // Corps et sujet du message String subject = getString("infoLetter.emailSubject") + ilp.getName(); // Email du publieur String from = getUserDetail().geteMail(); // create some properties and get the default Session Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication)); Session session = Session.getInstance(props, null); session.setDebug(isSmtpDebug); // print on the console all SMTP messages. SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "subject = " + subject); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "from = " + from); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host= " + host); try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, CharEncoding.UTF_8); ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId()); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg, I18NHelper.defaultLanguage); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (SimpleDocument content : contents) { AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(), content.getLanguage()); } mbp1.setDataHandler( new DataHandler(new ByteArrayDataSource( replaceFileServerWithLocal( IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server), MimeTypes.HTML_MIME_TYPE))); IOUtils.closeQuietly(buffer); // Fichiers joints WAPrimaryKey publiPK = ilp.getPK(); publiPK.setComponentName(getComponentId()); publiPK.setSpace(getSpaceId()); // create the Multipart and its parts to it String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related"); Multipart mp = new MimeMultipart(mimeMultipart); mp.addBodyPart(mbp1); // Images jointes List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null); for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); // For Displaying images in the mail mbp2.setFileName(attachment.getFilename()); mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } // Fichiers joints fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null); if (!fichiers.isEmpty()) { for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(attachment.getFilename()); // For Displaying images in the mail mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // create a Transport connection (TCP) Transport transport = session.getTransport("smtp"); InternetAddress[] address = new InternetAddress[1]; for (String email : emails) { try { address[0] = new InternetAddress(email); msg.setRecipients(Message.RecipientType.TO, address); // add Transport Listener to the transport connection. if (isSmtpAuthentication) { SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser); transport.connect(host, smtpPort, smtpUser, smtpPwd); msg.saveChanges(); } else { transport.connect(); } transport.sendMessage(msg, address); } catch (Exception ex) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "Email = " + email, new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, ex.getMessage(), ex)); emailErrors.add(email); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.EX_IGNORED", "ClosingTransport", e); } } } } } catch (Exception e) { throw new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, e.getMessage(), e); } } return emailErrors.toArray(new String[emailErrors.size()]); }
From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java
/** * Creates MimeMessage with supplied values * /*from w ww. j a v a 2 s. c om*/ * @param to - to email address * @param docType - String value for the attached document type * @param subject - Subject for the email * @param instructions - email body * @param content - content to be sent as attachment * @return MimeMessage instance */ public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content, String metadataXMl, String title, String indexBodyToken, String readmeToken) { final MimeMessage msg = mailSender.createMimeMessage(); UUID uniqueID = UUID.randomUUID(); tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID); try { msg.setFrom(new InternetAddress(getFrom())); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // The readable part final MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(instructions); mbp1.setHeader("Content-Type", "text/plain"); // The notification final MimeBodyPart mbp2 = new MimeBodyPart(); final String contentType = "application/xml; charset=UTF-8"; String extension; // HL7 messages should be a txt file, otherwise xml if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) { extension = TXT_EXT; } else { extension = XML_EXT; } final String fileName = docType + UUID.randomUUID() + extension; // final DataSource ds = new AttachmentDS(fileName, content, contentType); // mbp2.setDataHandler(new DataHandler(ds)); /******** START NHIN COMPLIANCE CHANGES *****/ boolean isTempZipFolderCreated = tempZipFolder.mkdirs(); if (!isTempZipFolderCreated) { LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); } String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM")); String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT")); indexFileString = StringUtils.replace(indexFileString, "@document_title@", title); indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString); readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString); // move template files & replace tokens // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false); // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false); // create sub-directories String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01"; File nhinSubDirectory = new File(nhinSubDirectoryPath); boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs(); if (!isNhinSubDirectoryCreated) { LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); } FileOutputStream metadataStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/METADATA.XML")); metadataStream.write(metadataXMl.getBytes()); metadataStream.flush(); metadataStream.close(); FileOutputStream documentStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/DOCUMENT" + extension)); documentStream.write(content.getBytes()); documentStream.flush(); documentStream.close(); String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP"; byte[] buffer = new byte[1024]; // FileOutputStream fos = new FileOutputStream(zipFile); // ZipOutputStream zos = new ZipOutputStream(fos); List<String> fileList = generateFileList(tempZipFolder); ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size()); ZipOutputStream zos = new ZipOutputStream(bout); // LOG.info("File List size: "+fileList.size()); for (String file : fileList) { ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } zos.closeEntry(); // remember close it zos.close(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); mbp2.setDataHandler(new DataHandler(source)); mbp2.setFileName(docType + ".ZIP"); /******** END NHIN COMPLIANCE CHANGES *****/ // mbp2.setFileName(fileName); // mbp2.setHeader("Content-Type", contentType); final Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); msg.setSentDate(new Date()); // FileUtils.deleteDirectory(tempZipFolder); } catch (AddressException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (MessagingException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (IOException e) { LOG.error(e.getMessage()); throw new ApplicationRuntimeException(e.getMessage()); } finally { //reset filelist contents fileList = new ArrayList<String>(); } return msg; }
From source file:net.spfbl.http.ServerHTTP.java
private static boolean enviarConfirmacaoDesbloqueio(String destinatario, String remetente, Locale locale) { if (Core.hasOutputSMTP() && Core.hasAdminEmail() && Domain.isEmail(remetente) && !NoReply.contains(remetente, true)) { try {//www .jav a 2s .c o m Server.logDebug("sending unblock confirmation by e-mail."); InternetAddress[] recipients = InternetAddress.parse(remetente); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setHeader("Date", Core.getEmailDate()); message.setFrom(Core.getAdminEmail()); message.setReplyTo(InternetAddress.parse(destinatario)); message.addRecipients(Message.RecipientType.TO, recipients); String subject; if (locale.getLanguage().toLowerCase().equals("pt")) { subject = "Confirmao de desbloqueio SPFBL"; } else { subject = "SPFBL unblocking confirmation"; } message.setSubject(subject); // Corpo da mensagem. StringBuilder builder = new StringBuilder(); builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); builder.append(" <title>"); builder.append(subject); builder.append("</title>\n"); loadStyleCSS(builder); builder.append(" </head>\n"); builder.append(" <body>\n"); builder.append(" <div id=\"container\">\n"); builder.append(" <div id=\"divlogo\">\n"); builder.append(" <img src=\"cid:logo\">\n"); builder.append(" </div>\n"); buildMessage(builder, subject); if (locale.getLanguage().toLowerCase().equals("pt")) { buildText(builder, "O destinatrio '" + destinatario + "' acabou de liberar o recebimento de suas mensagens."); buildText(builder, "Por favor, envie novamente a mensagem anterior."); } else { buildText(builder, "The recipient '" + destinatario + "' just released the receipt of your message."); buildText(builder, "Please send the previous message again."); } buildFooter(builder, locale); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); // Making HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8"); // Making logo part. MimeBodyPart logoPart = new MimeBodyPart(); File logoFile = getWebFile("logo.png"); logoPart.attachFile(logoFile); logoPart.setContentID("<logo>"); logoPart.addHeader("Content-Type", "image/png"); logoPart.setDisposition(MimeBodyPart.INLINE); // Join both parts. MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlPart); content.addBodyPart(logoPart); // Set multiplart content. message.setContent(content); message.saveChanges(); // Enviar mensagem. return Core.sendMessage(message, 5000); } catch (MessagingException ex) { return false; } catch (Exception ex) { Server.logError(ex); return false; } } else { return false; } }