List of usage examples for javax.mail.internet MimeBodyPart setText
@Override public void setText(String text, String charset) throws MessagingException
From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java
public MimeMessage getMimeMessage() throws MessagingException { if (attachments.isEmpty()) { switch (messageType) { case HTML: mimeMessage.setContent(messageBody, "text/html; charset=utf-8"); break; case TEXT: mimeMessage.setText(messageBody, "UTF-8"); mimeMessage.addHeader("Content-Transfer-Encoding", "quoted-printable"); break; }/*from www .j av a 2 s. c o m*/ } else { MimeBodyPart mimeBodyPart = new MimeBodyPart(); switch (messageType) { case HTML: mimeBodyPart.setContent(messageBody, "text/html; charset=utf-8"); break; case TEXT: mimeBodyPart.setText(messageBody, "UTF-8"); mimeMessage.addHeader("Content-Transfer-Encoding", "quoted-printable"); break; } mimeBodyPart.setDisposition(Part.INLINE); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); for (BodyPart attachmentPart : attachments) { multipart.addBodyPart(attachmentPart); } mimeMessage.setContent(multipart); } return mimeMessage; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/*from w w w .ja va 2 s . co m*/ * * @param multipart DOCUMENT ME! * @param text DOCUMENT ME! * @param charset DOCUMENT ME! * @param disposition DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static void attach(MimeMultipart multipart, String text, String charset, String disposition, boolean isHtml) throws MessagingException { int xid = multipart.getCount() + 1; MimeBodyPart xbody = new MimeBodyPart(); String xname = null; if (isHtml) { xname = "HTML" + xid + ".html"; xbody.setContent(text, "text/html" + "; charset=" + charset); xbody.setDescription("Html Attachment: " + xname, charset); } else { xname = "TEXT" + xid + ".txt"; xbody.setText(text, charset); xbody.setDescription("Text Attachment: " + xname, charset); } // UNDONE //xbody.setContentLanguage( String ); // this could be language from Locale //xbody.setContentMD5( String md5 ); // don't know about this yet xbody.setDisposition(disposition); MessageUtilities.setFileName(xbody, xname, charset); multipart.addBodyPart(xbody); }
From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java
private void addFormMultipart(HttpRequestInterface<?> request, MimeMultipart formMp, String name, String value) throws MessagingException { MimeBodyPart part = new MimeBodyPart(); if (value.startsWith("file:")) { String fileName = value.substring(5); File file = new File(fileName); part.setDisposition("form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\""); if (file.exists()) { part.setDataHandler(new DataHandler(new FileDataSource(file))); } else {/*from w ww. j av a2s . c om*/ for (Attachment attachment : request.getAttachments()) { if (attachment.getName().equals(fileName)) { part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment))); break; } } } part.setHeader("Content-Type", ContentTypeHandler.getContentTypeFromFilename(file.getName())); part.setHeader("Content-Transfer-Encoding", "binary"); } else { part.setDisposition("form-data; name=\"" + name + "\""); part.setText(value, System.getProperty("soapui.request.encoding", request.getEncoding())); } if (part != null) { formMp.addBodyPart(part); } }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
public byte[] getData(Context context) throws IOException, EngineException { HttpMethod method = null;//from www .j ava 2 s .c om try { // Fire event for plugins long t0 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context); // Retrieving httpState getHttpState(context); Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array..."); Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl); // Setting the referer referer = sUrl; URL url = null; url = new URL(sUrl); // Proxy configuration Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); Engine.logBeans.debug("(HttpConnector) Https: " + https); String host = ""; int port = -1; if (sUrl.toLowerCase().startsWith("https:")) { if (!https) { Engine.logBeans.debug("(HttpConnector) Setting up SSL properties"); certificateManager.collectStoreInformation(context); } url = new URL(sUrl); host = url.getHost(); port = url.getPort(); if (port == -1) port = 443; Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); Engine.logBeans .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) { Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, this.trustAllServerCertificates), port); hostConfiguration.setHost(host, port, myhttps); } sUrl = url.getFile(); Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl); } else { url = new URL(sUrl); host = url.getHost(); port = url.getPort(); Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); hostConfiguration.setHost(host, port); } AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction; // Retrieve HTTP method HttpMethodType httpVerb = httpTransaction.getHttpVerb(); String sHttpVerb = httpVerb.name(); final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb(); if (sCustomHttpVerb.length() > 0) { Engine.logBeans.debug( "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'"); switch (httpVerb) { case GET: method = new GetMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case POST: method = new PostMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case PUT: method = new PutMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case DELETE: method = new DeleteMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case HEAD: method = new HeadMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case OPTIONS: method = new OptionsMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case TRACE: method = new TraceMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; } } else { Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb); switch (httpVerb) { case GET: method = new GetMethod(sUrl); break; case POST: method = new PostMethod(sUrl); break; case PUT: method = new PutMethod(sUrl); break; case DELETE: method = new DeleteMethod(sUrl); break; case HEAD: method = new HeadMethod(sUrl); break; case OPTIONS: method = new OptionsMethod(sUrl); break; case TRACE: method = new TraceMethod(sUrl); break; } } // Setting HTTP parameters boolean hasUserAgent = false; for (List<String> httpParameter : httpParameters) { String key = httpParameter.get(0); String value = httpParameter.get(1); if (key.equalsIgnoreCase("host") && !value.equals(host)) { value = host; } if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) { method.setRequestHeader(key, value); } if (HeaderName.UserAgent.is(key)) { hasUserAgent = true; } } // set user-agent header if not found if (!hasUserAgent) { HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context)); } // Setting POST or PUT parameters if any Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data"); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method; AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; if (doMultipartFormData) { RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction .getVariable(Parameter.HttpBody.getName()); if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName()); String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName()); File file = new File(filepath); if (file.exists()) { HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType)); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } else { List<Part> parts = new LinkedList<Part>(); for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if ("POST".equals(httpVariable.getHttpMethod())) { Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addFormDataPart(parts, httpVariable, httpVariableValue); } } } else { addFormDataPart(parts, httpVariable, httpObjectVariableValue); } } } } MultipartRequestEntity mre = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams()); HeaderName.ContentType.setRequestHeader(method, mre.getContentType()); entityEnclosingMethod.setRequestEntity(mre); } } else if (MimeType.TextXml.is(contentType)) { final MimeMultipart[] mp = { null }; for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) { Engine.logBeans.trace( "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM"); MimeMultipart mimeMultipart = mp[0]; try { if (mimeMultipart == null) { Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request"); mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\""); MimeBodyPart bp = new MimeBodyPart(); bp.setText(postQuery, "UTF-8"); bp.setHeader(HeaderName.ContentType.value(), contentType); mimeMultipart.addBodyPart(bp); } Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addMtomPart(mimeMultipart, httpVariable, httpVariableValue); } } } else { addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue); } mp[0] = mimeMultipart; } catch (Exception e) { Engine.logBeans.warn( "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(), e); } } } } if (mp[0] == null) { entityEnclosingMethod.setRequestEntity( new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8")); } else { Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: " + mp[0].getContentType()); HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType()); entityEnclosingMethod.setRequestEntity(new RequestEntity() { @Override public void writeRequest(OutputStream outputStream) throws IOException { try { mp[0].writeTo(outputStream); } catch (MessagingException e) { new IOException(e); } } @Override public boolean isRepeatable() { return true; } @Override public String getContentType() { return mp[0].getContentType(); } @Override public long getContentLength() { return -1; } }); } } else { String charset = httpTransaction.getComputedUrlEncodingCharset(); HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset)); } } // Getting the result Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body"); byte[] result = executeMethod(method, context); Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0)); // Fire event for plugins long t1 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1); fireDataChanged(new ConnectorEvent(this, result)); return result; } finally { if (method != null) method.releaseConnection(); } }
From source file:net.wastl.webmail.plugins.SendMessage.java
public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head) throws WebMailException, ServletException { if (sess1 == null) { throw new WebMailException( "No session was given. If you feel this is incorrect, please contact your system administrator"); }/* w ww .ja va2 s .c o m*/ WebMailSession session = (WebMailSession) sess1; UserData user = session.getUser(); HTMLDocument content; Locale locale = user.getPreferredLocale(); /* Save message in case there is an error */ session.storeMessage(head); if (head.isContentSet("SEND")) { /* The form was submitted, now we will send it ... */ try { MimeMessage msg = new MimeMessage(mailsession); Address from[] = new Address[1]; try { /** * Why we need * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()? * * Because we specify client browser's encoding to UTF-8, IE seems * to send all data encoded in UTF-8. We have to transcode all byte * sequences we received to UTF-8, and next we encode those strings * using MimeUtility.encodeText() depending on user's locale. Since * MimeUtility.encodeText() is used to convert the strings into its * transmission format, finally we can use the strings in the * outgoing e-mail which relies on receiver's email agent to decode * the strings. * * As described in JavaMail document, MimeUtility.encodeText() conforms * to RFC2047 and as a result, we'll get strings like "=?Big5?B......". */ /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()), // MimeUtility.encodeText(session.getUser().getFullName())); from[0] = new InternetAddress( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale), TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null, locale)); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName()); } StringTokenizer t; try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("TO").trim(), ",;"); } /* Check To: field, when empty, throw an exception */ if (t.countTokens() < 1) { throw new MessagingException("The recipient field must not be empty!"); } Address to[] = new Address[t.countTokens()]; int i = 0; while (t.hasMoreTokens()) { to[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("CC").trim(), ",;"); } Address cc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { cc[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("BCC").trim(), ",;"); } Address bcc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { bcc[i] = new InternetAddress(t.nextToken().trim()); i++; } session.setSent(false); msg.addFrom(from); if (to.length > 0) { msg.addRecipients(Message.RecipientType.TO, to); } if (cc.length > 0) { msg.addRecipients(Message.RecipientType.CC, cc); } if (bcc.length > 0) { msg.addRecipients(Message.RecipientType.BCC, bcc); } msg.addHeader("X-Mailer", WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion()); String subject = null; if (!head.isContentSet("SUBJECT")) { subject = "no subject"; } else { try { // subject=MimeUtility.encodeText(head.getContent("SUBJECT")); subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1", locale); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); subject = head.getContent("SUBJECT"); } } msg.addHeader("Subject", subject); if (head.isContentSet("REPLY-TO")) { // msg.addHeader("Reply-To",head.getContent("REPLY-TO")); msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"), "ISO8859_1", locale)); } msg.setSentDate(new Date(System.currentTimeMillis())); String contnt = head.getContent("BODY"); //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset()); String charset = "utf-8"; MimeMultipart cont = new MimeMultipart(); MimeBodyPart txt = new MimeBodyPart(); // Transcode to UTF-8 contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8"); // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { txt.setText(contnt, "Big5"); txt.setHeader("Content-Type", "text/plain; charset=\"Big5\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } else { txt.setText(contnt, "utf-8"); txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } /* Add an advertisement if the administrator requested to do so */ cont.addBodyPart(txt); if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) { MimeBodyPart adv = new MimeBodyPart(); String file = ""; if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) { file = store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } else { file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator") + store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } String advcont = ""; try { BufferedReader fin = new BufferedReader(new FileReader(file)); String line = fin.readLine(); while (line != null && !line.equals("")) { advcont += line + "\n"; line = fin.readLine(); } fin.close(); } catch (IOException ex) { } /** * Transcode to UTF-8; Since advcont comes from file, we transcode * it from default encoding. */ // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { advcont = new String(advcont.getBytes(), "Big5"); adv.setText(advcont, "Big5"); adv.setHeader("Content-Type", "text/plain; charset=\"Big5\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } else { advcont = new String(advcont.getBytes(), "UTF-8"); adv.setText(advcont, "utf-8"); adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } cont.addBodyPart(adv); } for (String attachmentKey : session.getAttachments().keySet()) { ByteStore bs = session.getAttachment(attachmentKey); InternetHeaders ih = new InternetHeaders(); ih.addHeader("Content-Transfer-Encoding", "BASE64"); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(pin); /* This is used to write to the Pipe asynchronously to avoid blocking */ StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000); BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64")); encoder.write(bs.getBytes()); encoder.flush(); encoder.close(); //MimeBodyPart att1=sconn.getResult(); MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes()); if (bs.getDescription() != "") { att1.setDescription(bs.getDescription(), "utf-8"); } /** * As described in FileAttacher.java line #95, now we need to * encode the attachment file name. */ // att1.setFileName(bs.getName()); String fileName = bs.getName(); String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry()); String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null); if (encodedFileName.equals(fileName)) { att1.addHeader("Content-Type", bs.getContentType()); att1.setFileName(fileName); } else { att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset); encodedFileName = encodedFileName.substring(localeCharset.length() + 5, encodedFileName.length() - 2); encodedFileName = encodedFileName.replace('=', '%'); att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''" + encodedFileName); } cont.addBodyPart(att1); } msg.setContent(cont); // } msg.saveChanges(); boolean savesuccess = true; msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid")); if (session.getUser().wantsSaveSent()) { String folderhash = session.getUser().getSentFolder(); try { Folder folder = session.getFolder(folderhash); Message[] m = new Message[1]; m[0] = msg; folder.appendMessages(m); } catch (MessagingException e) { savesuccess = false; } catch (NullPointerException e) { // Invalid folder: savesuccess = false; } } boolean sendsuccess = false; try { Transport.send(msg); Address sent[] = new Address[to.length + cc.length + bcc.length]; int c1 = 0; int c2 = 0; for (c1 = 0; c1 < to.length; c1++) { sent[c1] = to[c1]; } for (c2 = 0; c2 < cc.length; c2++) { sent[c1 + c2] = cc[c2]; } for (int c3 = 0; c3 < bcc.length; c3++) { sent[c1 + c2 + c3] = bcc[c3]; } sendsuccess = true; throw new SendFailedException("success", new Exception("success"), sent, null, null); } catch (SendFailedException e) { session.handleTransportException(e); } //session.clearMessage(); content = new XHTMLDocument(session.getModel(), store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme())); // if(sendsuccess) session.clearWork(); } catch (Exception e) { log.error("Could not send messsage", e); throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")"); } } else if (head.isContentSet("ATTACH")) { /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to have two targets without Javascript) */ content = parent.getURLHandler().handleURL("/compose/attach", session, head); } else { throw new DocumentNotFoundException("Could not send message. (Reason: No content given)"); } return content; }
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.//w w w . j a va 2 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:org.agnitas.util.AgnUtils.java
/** * Sends an email in the correspondent type. *///from www .j a va2s. com public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject, String body_text, String body_html, int mailtype, String charset) { try { // create some properties and get the default Session Properties props = new Properties(); props.put("system.mail.host", getSmtpMailRelayHostname()); Session session = Session.getDefaultInstance(props, null); // session.setDebug(debug); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from_adr)); msg.setSubject(subject, charset); msg.setSentDate(new Date()); // Set to-recipient email addresses InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList); if (toAddresses != null && toAddresses.length > 0) { msg.setRecipients(Message.RecipientType.TO, toAddresses); } // Set cc-recipient email addresses InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList); if (ccAddresses != null && ccAddresses.length > 0) { msg.setRecipients(Message.RecipientType.CC, ccAddresses); } switch (mailtype) { case 0: msg.setText(body_text, charset); break; case 1: Multipart mp = new MimeMultipart("alternative"); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(body_text, charset); mp.addBodyPart(mbp); mbp = new MimeBodyPart(); mbp.setContent(body_html, "text/html; charset=" + charset); mp.addBodyPart(mbp); msg.setContent(mp); break; } Transport.send(msg); } catch (Exception e) { logger.error("sendEmail: " + e); logger.error(AgnUtils.getStackTrace(e)); return false; } return true; }
From source file:org.apache.axis.attachments.MimeUtils.java
/** * This routine will create a multipart object from the parts and the SOAP content. * @param env should be the text for the main root part. * @param parts contain a collection of the message parts. * * @return a new MimeMultipart object/* w w w . j a v a2 s . co m*/ * * @throws org.apache.axis.AxisFault */ public static javax.mail.internet.MimeMultipart createMP(String env, java.util.Collection parts, int sendType) throws org.apache.axis.AxisFault { javax.mail.internet.MimeMultipart multipart = null; try { String rootCID = SessionUtils.generateSessionId(); if (sendType == Attachments.SEND_TYPE_MTOM) { multipart = new javax.mail.internet.MimeMultipart("related;type=\"application/xop+xml\"; start=\"<" + rootCID + ">\"; start-info=\"text/xml; charset=utf-8\""); } else { multipart = new javax.mail.internet.MimeMultipart( "related; type=\"text/xml\"; start=\"<" + rootCID + ">\""); } javax.mail.internet.MimeBodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart(); messageBodyPart.setText(env, "UTF-8"); if (sendType == Attachments.SEND_TYPE_MTOM) { messageBodyPart.setHeader("Content-Type", "application/xop+xml; charset=utf-8; type=\"text/xml; charset=utf-8\""); } else { messageBodyPart.setHeader("Content-Type", "text/xml; charset=UTF-8"); } messageBodyPart.setHeader("Content-Id", "<" + rootCID + ">"); messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, "binary"); multipart.addBodyPart(messageBodyPart); for (java.util.Iterator it = parts.iterator(); it.hasNext();) { org.apache.axis.Part part = (org.apache.axis.Part) it.next(); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils .getActivationDataHandler(part); String contentID = part.getContentId(); messageBodyPart = new javax.mail.internet.MimeBodyPart(); messageBodyPart.setDataHandler(dh); String contentType = part.getContentType(); if ((contentType == null) || (contentType.trim().length() == 0)) { contentType = dh.getContentType(); } if ((contentType == null) || (contentType.trim().length() == 0)) { contentType = "application/octet-stream"; } messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentType); messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_ID, "<" + contentID + ">"); messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, "binary"); // Safe and fastest for anything other than mail; for (java.util.Iterator i = part.getNonMatchingMimeHeaders( new String[] { HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING }); i.hasNext();) { javax.xml.soap.MimeHeader header = (javax.xml.soap.MimeHeader) i.next(); messageBodyPart.setHeader(header.getName(), header.getValue()); } multipart.addBodyPart(messageBodyPart); } } catch (javax.mail.MessagingException e) { log.error(Messages.getMessage("javaxMailMessagingException00"), e); } return multipart; }
From source file:org.apache.camel.component.mail.MailBinding.java
protected void createMultipartAlternativeMessage(MimeMessage mimeMessage, MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException { MimeMultipart multipartAlternative = new MimeMultipart("alternative"); mimeMessage.setContent(multipartAlternative); MimeBodyPart plainText = new MimeBodyPart(); plainText.setText(getAlternativeBody(configuration, exchange), determineCharSet(configuration, exchange)); // remove the header with the alternative mail now that we got it // otherwise it might end up twice in the mail reader exchange.getIn().removeHeader(configuration.getAlternativeBodyHeader()); multipartAlternative.addBodyPart(plainText); // if there are no attachments, add the body to the same mulitpart message if (!exchange.getIn().hasAttachments()) { addBodyToMultipart(configuration, multipartAlternative, exchange); } else {//from www.j a v a2s. co m // if there are attachments, but they aren't set to be inline, add them to // treat them as normal. It will append a multipart-mixed with the attachments and the body text if (!configuration.isUseInlineAttachments()) { BodyPart mixedAttachments = new MimeBodyPart(); mixedAttachments.setContent(createMixedMultipartAttachments(configuration, exchange)); multipartAlternative.addBodyPart(mixedAttachments); } else { // if the attachments are set to be inline, attach them as inline attachments MimeMultipart multipartRelated = new MimeMultipart("related"); BodyPart related = new MimeBodyPart(); related.setContent(multipartRelated); multipartAlternative.addBodyPart(related); addBodyToMultipart(configuration, multipartRelated, exchange); addAttachmentsToMultipart(multipartRelated, Part.INLINE, exchange); } } }