List of usage examples for javax.mail.internet MimeBodyPart setDataHandler
@Override public void setDataHandler(DataHandler dh) throws MessagingException
From source file:Implement.Service.ProviderServiceImpl.java
@Override public boolean sendMail(HttpServletRequest request, String providerName, int providerID, String baseUrl) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtpm.csloxinfo.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }/*www . ja v a 2 s .co m*/ }); //Create data for referral java.util.Date date = new java.util.Date(); String s = providerID + (new Timestamp(date.getTime()).toString()); MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ProviderServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } m.update(s.getBytes(), 0, s.length()); String md5 = (new BigInteger(1, m.digest()).toString(16)); String title = "You have an invitation from your friend."; String receiver = request.getParameter("email"); // StringBuilder messageContentHtml = new StringBuilder(); // messageContentHtml.append(request.getParameter("message") + "<br />\n"); // messageContentHtml.append("You can become a provider from here: " + baseUrl + "/Common/Provider/SignupReferral/" + md5); // String messageContent = messageContentHtml.toString(); String emailContent = " <div style='background: url(cid:bg_Icon) no-repeat;background-color:#ebebec;text-align: center;width:610px;height:365px'>" + " <p style='font-size:16px;padding-top: 45px; padding-bottom: 15px;'>Your friend <b>" + providerName + "</b> has invited you to complete purchase via</p>" + " <a href='http://youtripper.com/Common/Provider/SignupReferral/" + md5 + "' style='width: 160px;height: 50px;border-radius: 5px;border: 0;" + " background-color: #ff514e;font-size: 14px;font-weight: bolder;color: #fff;display: block;line-height: 50px;margin: 0 auto;text-decoration:none;' >Refferal Link</a>" + " <p style='font-size:16px;margin:30px;'><b>" + providerName + "</b> will get 25 credit</p>" + " <a href='http://youtripper.com' target='_blank'><img src='cid:gift_Icon' width='90' height='90'></a>" + " <a href='http://youtripper.com' target='_blank' style='font-size:10px;color:#939598;text-decoration:none'><p>from www.youtripper.com</p></a>" + " " + " " + " </div>"; String path = System.getProperty("catalina.base"); MimeBodyPart backgroundImage = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png")); backgroundImage.setDataHandler(new DataHandler(source)); backgroundImage.setFileName("backgroundImage.png"); backgroundImage.setDisposition(MimeBodyPart.INLINE); backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid MimeBodyPart giftImage = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png")); giftImage.setDataHandler(new DataHandler(source)); giftImage.setFileName("emailGift.png"); giftImage.setDisposition(MimeBodyPart.INLINE); giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(emailContent, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1); mp.addBodyPart(backgroundImage); mp.addBodyPart(giftImage); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver)); message.setSubject(title); message.setContent(mp); message.saveChanges(); Transport.send(message); ReferralDTO referral = new ReferralDTO(providerID, receiver, String.valueOf(System.currentTimeMillis()), md5, 0); referralDAO.insertNewReferral(referral); return true; }
From source file:org.kuali.test.utils.Utils.java
/** * //from w w w . jav a2s . c o m * @param configuration * @param overrideEmail * @param testSuite * @param testHeader * @param testResults * @param errorCount * @param warningCount * @param successCount */ public static void sendMail(KualiTestConfigurationDocument.KualiTestConfiguration configuration, String overrideEmail, TestSuite testSuite, TestHeader testHeader, List<File> testResults, int errorCount, int warningCount, int successCount) { if (StringUtils.isNotBlank(configuration.getEmailSetup().getFromAddress()) && StringUtils.isNotBlank(configuration.getEmailSetup().getMailHost())) { String[] toAddresses = getEmailToAddresses(configuration, testSuite, testHeader); if (toAddresses.length > 0) { Properties props = new Properties(); props.put("mail.smtp.host", configuration.getEmailSetup().getMailHost()); Session session = Session.getDefaultInstance(props, null); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(configuration.getEmailSetup().getFromAddress())); if (StringUtils.isBlank(overrideEmail)) { for (String recipient : toAddresses) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } } else { StringTokenizer st = new StringTokenizer(overrideEmail, ","); while (st.hasMoreTokens()) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(st.nextToken())); } } StringBuilder subject = new StringBuilder(configuration.getEmailSetup().getSubject()); subject.append(" - Platform: "); if (testSuite != null) { subject.append(testSuite.getPlatformName()); subject.append(", TestSuite: "); subject.append(testSuite.getName()); } else { subject.append(testHeader.getPlatformName()); subject.append(", Test: "); subject.append(testHeader.getTestName()); } subject.append(" - [errors="); subject.append(errorCount); subject.append(", warnings="); subject.append(warningCount); subject.append(", successes="); subject.append(successCount); subject.append("]"); msg.setSubject(subject.toString()); StringBuilder msgtxt = new StringBuilder(256); msgtxt.append("Please see test output in the following attached files:\n"); for (File f : testResults) { msgtxt.append(f.getName()); msgtxt.append("\n"); } // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msgtxt.toString()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); for (File f : testResults) { if (f.exists() && f.isFile()) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message mbp2.setDataHandler(new DataHandler(new FileDataSource(f))); mbp2.setFileName(f.getName()); mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException ex) { LOG.warn(ex.toString(), ex); } } } }
From source file:nl.nn.adapterframework.http.HttpSender.java
protected void addMtomMultiPartToPostMethod(PostMethod hmethod, String message, ParameterValueList parameters, ParameterResolutionContext prc) throws SenderException, MessagingException, IOException { MyMimeMultipart mimeMultipart = new MyMimeMultipart("related"); String start = null;//from w ww . j a va 2 s . c om if (StringUtils.isNotEmpty(getInputMessageParam())) { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(message, "application/xop+xml; charset=UTF-8; type=\"text/xml\""); start = "<" + getInputMessageParam() + ">"; mimeBodyPart.setContentID(start); ; mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + getInputMessageParam() + "] with value [" + message + "]"); } if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { ParameterValue pv = parameters.getParameterValue(i); String paramType = pv.getDefinition().getType(); String name = pv.getDefinition().getName(); if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) { Object value = pv.getValue(); if (value instanceof FileInputStream) { FileInputStream fis = (FileInputStream) value; String fileName = null; String sessionKey = pv.getDefinition().getSessionKey(); if (sessionKey != null) { fileName = (String) prc.getSession().get(sessionKey + "Name"); } MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, "application/octet-stream"); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(fileName); mimeBodyPart.setContentID("<" + name + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + name + "] with value [" + value + "] and name [" + fileName + "]"); } else { throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass() + "] for parameter [" + name + "]"); } } else { String value = pv.asStringValue(""); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(value, "text/xml"); if (start == null) { start = "<" + name + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + name + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug( getLogPrefix() + "appended (string)part [" + name + "] with value [" + value + "]"); } } } if (StringUtils.isNotEmpty(getMultipartXmlSessionKey())) { String multipartXml = (String) prc.getSession().get(getMultipartXmlSessionKey()); if (StringUtils.isEmpty(multipartXml)) { log.warn(getLogPrefix() + "sessionKey [" + getMultipartXmlSessionKey() + "] is empty"); } else { Element partsElement; try { partsElement = XmlUtils.buildElement(multipartXml); } catch (DomBuilderException e) { throw new SenderException(getLogPrefix() + "error building multipart xml", e); } Collection parts = XmlUtils.getChildTags(partsElement, "part"); if (parts == null || parts.size() == 0) { log.warn(getLogPrefix() + "no part(s) in multipart xml [" + multipartXml + "]"); } else { int c = 0; Iterator iter = parts.iterator(); while (iter.hasNext()) { c++; Element partElement = (Element) iter.next(); //String partType = partElement.getAttribute("type"); String partName = partElement.getAttribute("name"); String partMimeType = partElement.getAttribute("mimeType"); String partSessionKey = partElement.getAttribute("sessionKey"); Object partObject = prc.getSession().get(partSessionKey); if (partObject instanceof FileInputStream) { FileInputStream fis = (FileInputStream) partObject; MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, (partMimeType == null ? "application/octet-stream" : partMimeType)); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(partName); mimeBodyPart.setContentID("<" + partName + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + partSessionKey + "] with value [" + partObject + "] and name [" + partName + "]"); } else { String partValue = (String) prc.getSession().get(partSessionKey); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(partValue, "text/xml"); if (start == null) { start = "<" + partName + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + partName + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + partSessionKey + "] with value [" + partValue + "]"); } } } } } MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties())); mimeMessage.setContent(mimeMultipart); mimeMessage.saveChanges(); InputStreamRequestEntity request = new InputStreamRequestEntity(mimeMessage.getInputStream()); hmethod.setRequestEntity(request); String contentTypeMtom = "multipart/related; type=\"application/xop+xml\"; start=\"" + start + "\"; start-info=\"text/xml\"; boundary=\"" + mimeMultipart.getBoundary() + "\""; Header header = new Header("Content-Type", contentTypeMtom); hmethod.addRequestHeader(header); }
From source file:dtw.webmail.util.FormdataMultipart.java
/** * Processes a body part of the form-data. * Extracts parameters and set values, and * leaves over the attachments./* w w w. j a v a 2 s .c om*/ * * @param mbp the <tt>MimeBodyPart</tt> to be processed. * * @throws IOException if i/o operations fail. * @throws MessagingException if parsing or part handling with * Mail API classes fails. */ private void processBodyPart(MimeBodyPart mbp) throws MessagingException, IOException { //String contenttype=new String(mbp.getContentType()); //JwmaKernel.getReference().debugLog().write("Processing "+contenttype); //check if a content-type is given String[] cts = mbp.getHeader("Content-Type"); if (cts == null || cts.length == 0) { //this is a parameter, get it out and //remove the part. String controlname = extractName((mbp.getHeader("Content-Disposition"))[0]); //JwmaKernel.getReference().debugLog().write("Processing control:"+controlname); //retrieve value observing encoding InputStream in = mbp.getInputStream(); String[] encoding = mbp.getHeader("Content-Transfer-Encoding"); if (encoding != null && encoding.length > 0) { in = MimeUtility.decode(in, encoding[0]); } String value = extractValue(in); if (value != null || !value.trim().equals("")) { addParameter(controlname, value); } //flag removal m_Removed = true; removeBodyPart(mbp); } else { String filename = extractFileName((mbp.getHeader("Content-Disposition"))[0]); //normally without file the control should be not successful. //but neither netscape nor mircosoft iexploder care much. //the only feature is an empty filename. if (filename.equals("")) { //kick it out too m_Removed = true; removeBodyPart(mbp); } else { //JwmaKernel.getReference().debugLog().write("Incoming filename="+filename); //IExploder sends files with complete path. //jwma doesnt want this. int lastindex = filename.lastIndexOf("\\"); if (lastindex != -1) { filename = filename.substring(lastindex + 1, filename.length()); } //JwmaKernel.getReference().debugLog().write("Outgoing filename="+filename); //Observe a possible encoding InputStream in = mbp.getInputStream(); String[] encoding = mbp.getHeader("Content-Transfer-Encoding"); if (encoding != null && encoding.length > 0) { in = MimeUtility.decode(in, encoding[0]); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputStream out = (OutputStream) bout; int i = 0; while ((i = in.read()) != -1) { //maybe more efficient in buffers, but well out.write(i); } out.flush(); out.close(); //create the datasource MimeBodyPartDataSource mbpds = new MimeBodyPartDataSource( // contenttype,filename,bout.toByteArray() cts[0], filename, bout.toByteArray()); //Re-set the Content-Disposition header, in case //the file name was changed mbp.removeHeader("Content-Disposition"); mbp.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); //set a base64 transferencoding und the data handler mbp.addHeader("Content-Transfer-Encoding", "base64"); mbp.setDataHandler(new DataHandler(mbpds)); } } }
From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java
/** * Creates MimeMessage with supplied values * /*from w w w . 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:de.innovationgate.wgpublisher.WGACore.java
public void send(WGAMailNotification notification) { WGAMailConfiguration config = getMailConfig(); if (config != null && config.isEnableAdminNotifications()) { try {// w ww . j a va 2s .c o m Message msg = new MimeMessage(config.createMailSession()); // set recipient and from address String toAddress = config.getToAddress(); if (toAddress == null) { getLog().error( "Unable to send wga admin notification because no recipient address is configured"); return; } msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); InternetAddress[] fromAddr = new InternetAddress[1]; fromAddr[0] = new InternetAddress(config.getFromAddress()); msg.addFrom(fromAddr); msg.setSentDate(new Date()); InetAddress localMachine = InetAddress.getLocalHost(); String hostname = localMachine.getHostName(); String serverName = getWgaConfiguration().getServerName(); if (serverName == null) { serverName = hostname; } msg.setSubject(notification.getSubject()); msg.setHeader(WGAMailNotification.HEADERFIELD_TYPE, notification.getType()); MimeMultipart content = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); StringBuffer strBody = new StringBuffer(); strBody.append("<html><head></head><body style=\"color:#808080\">"); strBody.append(notification.getMessage()); String rootURL = getWgaConfiguration().getRootURL(); if (rootURL != null) { //strBody.append("<br><br>"); strBody.append("<p><a href=\"" + rootURL + "/plugin-admin\">" + WGABrand.getName() + " admin client ...</a></p>"); } // append footer strBody.append("<br><br><b>System information:</b><br><br>"); strBody.append("<b>Server:</b> " + serverName + " / " + WGACore.getReleaseString() + "<br>"); strBody.append("<b>Host:</b> " + hostname + "<br>"); strBody.append("<b>Operation System:</b> " + System.getProperty("os.name") + " Version " + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")<br>"); strBody.append("<b>Java virtual machine:</b> " + System.getProperty("java.vm.name") + " Version " + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor") + ")"); strBody.append("</body></html>"); body.setText(strBody.toString()); body.setHeader("MIME-Version", "1.0"); body.setHeader("Content-Type", "text/html"); content.addBodyPart(body); AppLog appLog = WGA.get(this).service(AppLog.class); if (notification.isAttachLogfile()) { MimeBodyPart attachmentBody = new MimeBodyPart(); StringWriter applog = new StringWriter(); int applogSize = appLog.getLinesCount(); int offset = applogSize - notification.getLogfileLines(); if (offset < 0) { offset = 1; } appLog.writePage(offset, notification.getLogfileLines(), applog, LogLevel.LEVEL_INFO, false); attachmentBody.setDataHandler(new DataHandler(applog.toString(), "text/plain")); attachmentBody.setFileName("wga.log"); content.addBodyPart(attachmentBody); } msg.setContent(content); // Send mail Thread mailThread = new Thread(new AsyncMailSender(msg), "WGAMailSender"); mailThread.start(); } catch (Exception e) { getLog().error("Unable to send wga admin notification.", e); } } }
From source file:com.sonicle.webtop.mail.Service.java
public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave) throws Exception { MimeMessage msg = null;/*from w w w . j a va2 s . co m*/ boolean success = true; String[] to = SimpleMessage.breakAddr(smsg.getTo()); String[] cc = SimpleMessage.breakAddr(smsg.getCc()); String[] bcc = SimpleMessage.breakAddr(smsg.getBcc()); String replyTo = smsg.getReplyTo(); msg = new MimeMessage(mainAccount.getMailSession()); msg.setFrom(getInternetAddress(from)); InternetAddress ia = null; //set the TO recipient for (int q = 0; q < to.length; q++) { // Service.logger.debug("to["+q+"]="+to[q]); to[q] = to[q].replace(',', ' '); try { ia = getInternetAddress(to[q]); } catch (AddressException exc) { throw new AddressException(to[q]); } msg.addRecipient(Message.RecipientType.TO, ia); } //set the CC recipient for (int q = 0; q < cc.length; q++) { cc[q] = cc[q].replace(',', ' '); try { ia = getInternetAddress(cc[q]); } catch (AddressException exc) { throw new AddressException(cc[q]); } msg.addRecipient(Message.RecipientType.CC, ia); } //set BCC recipients for (int q = 0; q < bcc.length; q++) { bcc[q] = bcc[q].replace(',', ' '); try { ia = getInternetAddress(bcc[q]); } catch (AddressException exc) { throw new AddressException(bcc[q]); } msg.addRecipient(Message.RecipientType.BCC, ia); } //set reply to addr if (replyTo != null && replyTo.length() > 0) { Address[] replyaddr = new Address[1]; replyaddr[0] = getInternetAddress(replyTo); msg.setReplyTo(replyaddr); } //add any header String headerLines[] = smsg.getHeaderLines(); for (int i = 0; i < headerLines.length; ++i) { if (!headerLines[i].startsWith("Sonicle-reply-folder")) { msg.addHeaderLine(headerLines[i]); } } //add reply/references String inreplyto = smsg.getInReplyTo(); String references[] = smsg.getReferences(); String replyfolder = smsg.getReplyFolder(); if (inreplyto != null) { msg.setHeader("In-Reply-To", inreplyto); } if (references != null && references[0] != null) { msg.setHeader("References", references[0]); } if (tosave) { if (replyfolder != null) { msg.setHeader("Sonicle-reply-folder", replyfolder); } msg.setHeader("Sonicle-draft", "true"); } //add forward data String forwardedfrom = smsg.getForwardedFrom(); String forwardedfolder = smsg.getForwardedFolder(); if (forwardedfrom != null) { msg.setHeader("Forwarded-From", forwardedfrom); } if (tosave) { if (forwardedfolder != null) { msg.setHeader("Sonicle-forwarded-folder", forwardedfolder); } msg.setHeader("Sonicle-draft", "true"); } //set the subject String subject = smsg.getSubject(); try { //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null); subject = MimeUtility.encodeText(smsg.getSubject()); } catch (Exception exc) { } msg.setSubject(subject); //set priority int priority = smsg.getPriority(); if (priority != 3) { msg.setHeader("X-Priority", "" + priority); //set receipt } String receiptTo = from; try { receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null); } catch (Exception exc) { } if (smsg.getReceipt()) { msg.setHeader("Disposition-Notification-To", from); //see if there are any new attachments for the message } int noAttach; int newAttach; if (attachments == null) { newAttach = 0; } else { newAttach = attachments.size(); } //get the array of the old attachments Part[] oldParts = smsg.getAttachments(); //check if there are old attachments if (oldParts == null) { noAttach = 0; } else { //old attachments exist noAttach = oldParts.length; } if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) { // create the main Multipart MimeMultipart mp = new MimeMultipart("mixed"); MimeMultipart unrelated = null; String textcontent = smsg.getTextContent(); //if is text, or no alternative text is available, add the content as one single body part //else create a multipart/alternative with both rich and text mime content if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); mp.addBodyPart(mbp1); } else { MimeMultipart alternative = new MimeMultipart("alternative"); //the rich part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); //the text part MimeBodyPart mbp1 = new MimeBodyPart(); /* ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length()); com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos); for(int i=0;i<textcontent.length();++i) { try { qpe.write(textcontent.charAt(i)); } catch(IOException exc) { Service.logger.error("Exception",exc); } } textcontent=new String(bos.toByteArray());*/ mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8")); // mbp1.setHeader("Content-transfer-encoding","quoted-printable"); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } if (noAttach > 0) { //if there are old attachments // create the parts with the attachments //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach]; //Part[] mbps2 = new Part[noAttach]; //for(int e = 0;e < noAttach;e++) { // mbps2[e] = (Part)oldParts[e]; //}//end for e //add the old attachment parts for (int r = 0; r < noAttach; r++) { Object content = null; String contentType = null; String contentFileName = null; if (oldParts[r] instanceof Message) { // Service.logger.debug("Attachment is a message"); Message msgpart = (Message) oldParts[r]; MimeMessage mm = new MimeMessage(mainAccount.getMailSession()); mm.addFrom(msgpart.getFrom()); mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO)); mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC)); mm.setRecipients(Message.RecipientType.BCC, msgpart.getRecipients(Message.RecipientType.BCC)); mm.setReplyTo(msgpart.getReplyTo()); mm.setSentDate(msgpart.getSentDate()); mm.setSubject(msgpart.getSubject()); mm.setContent(msgpart.getContent(), msgpart.getContentType()); content = mm; contentType = "message/rfc822"; } else { // Service.logger.debug("Attachment is not a message"); content = oldParts[r].getContent(); if (!(content instanceof MimeMultipart)) { contentType = oldParts[r].getContentType(); contentFileName = oldParts[r].getFileName(); } } MimeBodyPart mbp = new MimeBodyPart(); if (contentFileName != null) { mbp.setFileName(contentFileName); // Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName); contentType += "; name=\"" + contentFileName + "\""; } if (content instanceof MimeMultipart) mbp.setContent((MimeMultipart) content); else mbp.setDataHandler(new DataHandler(content, contentType)); mp.addBodyPart(mbp); } } //end if, adding old attachments if (newAttach > 0) { //if there are new attachments // create the parts with the attachments MimeBodyPart[] mbps = new MimeBodyPart[newAttach]; for (int e = 0; e < newAttach; e++) { mbps[e] = new MimeBodyPart(); // attach the file to the message JsAttachment attach = (JsAttachment) attachments.get(e); UploadedFile upfile = getUploadedFile(attach.uploadId); FileDataSource fds = new FileDataSource(upfile.getFile()); mbps[e].setDataHandler(new DataHandler(fds)); // filename starts has format: // "_" + userid + sessionId + "_" + filename // if (attach.inline) { mbps[e].setDisposition(Part.INLINE); } String contentFileName = attach.fileName.trim(); mbps[e].setFileName(contentFileName); String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\""; mbps[e].setHeader("Content-type", contentType); if (attach.cid != null && attach.cid.trim().length() > 0) { mbps[e].setHeader("Content-ID", "<" + attach.cid + ">"); mbps[e].setHeader("X-Attachment-Id", attach.cid); mbps[e].setDisposition(Part.INLINE); if (unrelated == null) unrelated = new MimeMultipart("mixed"); } } //end for e //add the new attachment parts if (unrelated == null) { for (int r = 0; r < newAttach; r++) mp.addBodyPart(mbps[r]); } else { //mp becomes the related part with text parts and cids MimeMultipart related = mp; related.setSubType("related"); //nest the related part into the mixed part mp = unrelated; MimeBodyPart mbd = new MimeBodyPart(); mbd.setContent(related); mp.addBodyPart(mbd); for (int r = 0; r < newAttach; r++) { if (mbps[r].getHeader("Content-ID") != null) { related.addBodyPart(mbps[r]); } else { mp.addBodyPart(mbps[r]); } } } } //end if, adding new attachments // // msg.addHeaderLine("This is a multi-part message in MIME format."); // add the Multipart to the message msg.setContent(mp); } else { //end if newattach msg.setText(smsg.getContent()); } //singlepart message msg.setSentDate(new java.util.Date()); return msg; }