List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:com.nridge.core.app.mail.MailManager.java
/** * If the property "delivery_enabled" is <i>true</i>, then this method * will generate an email message that includes subject, message and * attachments to the recipient list. You can use the convenience * methods <i>lookupFromAddress()</i>, <i>createRecipientList()</i> * and <i>createAttachmentList()</i> for parameter building assistance. * * @param aFromAddress Source email address. * @param aRecipientList List of recipient email addresses. * @param aSubject Subject of the email message. * @param aMessage Messsage.//w w w .j a v a 2s . co m * @param anAttachmentFiles List of file attachments or <i>null</i> for none. * * @see <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm">JavaMail API Attachments</a> * @see <a href="https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r">JavaMail API MIME Types</a> * * @throws IOException I/O related error condition. * @throws NSException Missing configuration properties. * @throws MessagingException Message subsystem error condition. */ public void sendMessage(String aFromAddress, ArrayList<String> aRecipientList, String aSubject, String aMessage, ArrayList<String> anAttachmentFiles) throws IOException, NSException, MessagingException { InternetAddress internetAddressFrom, internetAddressTo; Logger appLogger = mAppMgr.getLogger(this, "sendMessage"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (isCfgStringTrue("delivery_enabled")) { if ((StringUtils.isNotEmpty(aFromAddress)) && (aRecipientList.size() > 0) && (StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) { initialize(); Message mimeMessage = new MimeMessage(mMailSession); internetAddressFrom = new InternetAddress(aFromAddress); mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom }); for (String mailAddressTo : aRecipientList) { internetAddressTo = new InternetAddress(mailAddressTo); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo); } mimeMessage.setSubject(aSubject); // The following logic create a multi-part message and adds the attachment to it. BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(aMessage); // messageBodyPart.setContent(aMessage, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); if ((anAttachmentFiles != null) && (anAttachmentFiles.size() > 0)) { for (String pathFileName : anAttachmentFiles) { File attachmentFile = new File(pathFileName); if (attachmentFile.exists()) { messageBodyPart = new MimeBodyPart(); DataSource fileDataSource = new FileDataSource(pathFileName); messageBodyPart.setDataHandler(new DataHandler(fileDataSource)); messageBodyPart.setFileName(attachmentFile.getName()); multipart.addBodyPart(messageBodyPart); } } appLogger.debug(String.format("Mail Message (%s): %s - with attachments", aSubject, aMessage)); } else appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage)); mimeMessage.setContent(multipart); Transport.send(mimeMessage); } else throw new NSException("Valid from, recipient, subject and message are required parameters."); } else appLogger.warn("Email delivery is not enabled - no message will be sent."); appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java
/** * Adds a simple MimeBodyPart from an attachment *///from w ww. j a v a 2 s. c om public static void addSingleAttachment(MimeMultipart mp, StringToStringMap contentIds, Attachment att) throws MessagingException { String contentType = att.getContentType(); MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart() : new PreencodedMimeBodyPart("binary"); part.setDataHandler(new DataHandler(new AttachmentDataSource(att))); initPartContentId(contentIds, part, att, false); mp.addBodyPart(part); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from w ww . j a va 2 s . com * * @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.youxifan.utils.EMail.java
/** * Set the message content//from ww w.j av a 2 s. co m * @throws MessagingException * @throws IOException */ private void setContent() throws MessagingException, IOException { // Local Character Set String charSetName; if (m_encoding == null) { charSetName = System.getProperty("file.encoding"); // Cp1252 if (charSetName == null || charSetName.length() == 0) charSetName = "UTF-8"; // WebEnv.ENCODING - alternative iso-8859-1 } else { charSetName = m_encoding; } m_msg.setSubject(getSubject(), charSetName); // Simple Message if (m_attachments == null || m_attachments.size() == 0) { if (m_messageHTML == null || m_messageHTML.length() == 0) m_msg.setText(getMessageCRLF(), charSetName); else m_msg.setDataHandler( new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html"))); // log.info("(simple) " + getSubject()); } else // Multi part message *************************************** { // First Part - Message MimeBodyPart mbp_1 = new MimeBodyPart(); mbp_1.setText(""); if (m_messageHTML == null || m_messageHTML.length() == 0) mbp_1.setText(getMessageCRLF(), charSetName); else mbp_1.setDataHandler( new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html"))); // Create Multipart and its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp_1); log.info("(multi) " + getSubject() + " - " + mbp_1); // for all attachments for (int i = 0; i < m_attachments.size(); i++) { Object attachment = m_attachments.get(i); DataSource ds = null; if (attachment instanceof File) { File file = (File) attachment; if (file.exists()) ds = new FileDataSource(file); else { log.warn("File does not exist: " + file); continue; } } else if (attachment instanceof URL) { URL url = (URL) attachment; ds = new URLDataSource(url); } else if (attachment instanceof DataSource) ds = (DataSource) attachment; else { log.warn("Attachement type unknown: " + attachment); continue; } // Attachment Part MimeBodyPart mbp_2 = new MimeBodyPart(); mbp_2.setDataHandler(new DataHandler(ds)); mbp_2.setFileName(ds.getName()); log.info("Added Attachment " + ds.getName() + " - " + mbp_2); mp.addBodyPart(mbp_2); } // Add to Message m_msg.setContent(mp); } // multi=part }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Writes a passed payload data to the passed message object. Could be called from either the MDN * processing or the message processing/* www . j av a2 s.c o m*/ */ public void writePayloadsToMessage(byte[] data, AS2Message message, Properties header) throws Exception { ByteArrayOutputStream payloadOut = new ByteArrayOutputStream(); MimeMessage testMessage = new MimeMessage(Session.getInstance(System.getProperties()), new ByteArrayInputStream(data)); //multiple attachments? if (testMessage.isMimeType("multipart/*")) { this.writePayloadsToMessage(testMessage, message, header); return; } InputStream payloadIn = null; AS2Info info = message.getAS2Info(); if (info instanceof AS2MessageInfo && info.getSignType() == AS2Message.SIGNATURE_NONE && ((AS2MessageInfo) info).getCompressionType() == AS2Message.COMPRESSION_NONE) { payloadIn = new ByteArrayInputStream(data); } else if (testMessage.getSize() > 0) { payloadIn = testMessage.getInputStream(); } else { payloadIn = new ByteArrayInputStream(data); } this.copyStreams(payloadIn, payloadOut); payloadOut.flush(); payloadOut.close(); byte[] payloadData = payloadOut.toByteArray(); AS2Payload as2Payload = new AS2Payload(); as2Payload.setData(payloadData); String contentIdHeader = header.getProperty("content-id"); if (contentIdHeader != null) { as2Payload.setContentId(contentIdHeader); } String contentTypeHeader = header.getProperty("content-type"); if (contentTypeHeader != null) { as2Payload.setContentType(contentTypeHeader); } try { as2Payload.setOriginalFilename(testMessage.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } if (as2Payload.getOriginalFilename() == null) { String filenameHeader = header.getProperty("content-disposition"); if (filenameHeader != null) { //test part for convinience: extract file name MimeBodyPart filenamePart = new MimeBodyPart(); filenamePart.setHeader("content-disposition", filenameHeader); try { as2Payload.setOriginalFilename(filenamePart.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } } } message.addPayload(as2Payload); }
From source file:lucee.runtime.net.smtp.SMTPClient.java
private MimeBodyPart getHTMLText() throws MessagingException { MimeBodyPart html = new MimeBodyPart(); fillHTMLText(html); return html; }
From source file:org.pentaho.di.trans.steps.mail.Mail.java
public void sendMail(Object[] r, String server, int port, String senderAddress, String senderName, String destination, String destinationCc, String destinationBCc, String contactPerson, String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject, String comment, String replyToAddresses) throws Exception { // Send an e-mail... // create some properties and get the default Session String protocol = "smtp"; if (meta.isUsingSecureAuthentication()) { // PDI-2955 // if (meta.isUsingAuthentication()) { if (meta.getSecureConnectionType().equals("TLS")) { // Allow TLS authentication data.props.put("mail.smtp.starttls.enable", "true"); } else {// w ww .ja v a 2s . c o m protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown data.props.put("mail.smtps.quitwait", "false"); } } data.props.put("mail." + protocol + ".host", server); if (port != -1) { data.props.put("mail." + protocol + ".port", "" + port); // needs to be supplied as a string, not as an integer } if (isDebug()) { data.props.put("mail.debug", "true"); } if (meta.isUsingAuthentication()) { data.props.put("mail." + protocol + ".auth", "true"); } Session session = Session.getInstance(data.props); session.setDebug(isDebug()); // create a message Message msg = new MimeMessage(session); // set message priority if (meta.isUsePriority()) { String priority_int = "1"; if (meta.getPriority().equals("low")) { priority_int = "3"; } if (meta.getPriority().equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low. msg.setHeader("Importance", meta.getImportance()); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. msg.setHeader("Sensitivity", meta.getSensitivity()); // Possible values are normal, personal, private, company-confidential } // set Email sender String email_address = senderAddress; if (!Const.isEmpty(email_address)) { // get sender name if (!Const.isEmpty(senderName)) { email_address = senderName + '<' + email_address + '>'; } msg.setFrom(new InternetAddress(email_address)); } else { throw new MessagingException(BaseMessages.getString(PKG, "Mail.Error.ReplyEmailNotFilled")); } // Set reply to if (!Const.isEmpty(replyToAddresses)) { // get replay to // Split the mail-address: space separated String[] reply_Address_List = replyToAddresses.split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) { address[i] = new InternetAddress(reply_Address_List[i]); } // To add the real reply-to msg.setReplyTo(address); } // Split the mail-address: space separated String[] destinations = destination.split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) { address[i] = new InternetAddress(destinations[i]); } msg.setRecipients(Message.RecipientType.TO, address); String realdestinationCc = destinationCc; if (!Const.isEmpty(realdestinationCc)) { // Split the mail-address Cc: space separated String[] destinationsCc = realdestinationCc.split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) { addressCc[i] = new InternetAddress(destinationsCc[i]); } msg.setRecipients(Message.RecipientType.CC, addressCc); } String realdestinationBCc = destinationBCc; if (!Const.isEmpty(realdestinationBCc)) { // Split the mail-address BCc: space separated String[] destinationsBCc = realdestinationBCc.split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) { addressBCc[i] = new InternetAddress(destinationsBCc[i]); } msg.setRecipients(Message.RecipientType.BCC, addressBCc); } if (mailsubject != null) { msg.setSubject(mailsubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(comment).append(Const.CR).append(Const.CR); } if (meta.getIncludeDate()) { messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); } if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) { messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.PersonToContact") + " : ") .append(contactPerson).append(Const.CR); messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.Tel") + " : ").append(contactPhone) .append(Const.CR); messageText.append(Const.CR); } data.parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part if (meta.isUseHTML()) { if (!Const.isEmpty(meta.getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else { part1.setText(messageText.toString()); } data.parts.addBodyPart(part1); if (meta.isAttachContentFromField()) { // attache file content addAttachedContent(data.previousRowMeta.getString(r, data.IndexOfAttachedFilename), data.previousRowMeta.getString(r, data.indexOfAttachedContent)); } else { // attached files if (meta.isDynamicFilename()) { setAttachedFilesList(r, log); } else { setAttachedFilesList(null, log); } } // add embedded images addImagePart(); if (data.nrEmbeddedImages > 0 && data.nrattachedFiles == 0) { // If we need to embedd images... // We need to create a "multipart/related" message. // otherwise image will appear as attached file data.parts.setSubType("related"); } msg.setContent(data.parts); Transport transport = null; try { transport = session.getTransport(protocol); if (meta.isUsingAuthentication()) { if (port != -1) { transport.connect(Const.NVL(server, ""), port, Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } else { transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) { transport.close(); } } }
From source file:lucee.runtime.net.smtp.SMTPClient.java
private MimeBodyPart getPlainText() throws MessagingException { MimeBodyPart plain = new MimeBodyPart(); fillPlainText(plain); return plain; }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server//ww w . j av a 2 s.c o m * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, @SuppressWarnings("unused") final String port, @SuppressWarnings("unused") final String security, final File fileAttachment) { String userName = uName; String password = pWord; Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); Properties props = System.getProperties(); props.put("mail.smtp.host", host); //$NON-NLS-1$ props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ boolean usingSSL = false; if (usingSSL) { props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } Session session = Session.getInstance(props, null); session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } // set the Date: header msg.setSentDate(new Date()); // send the message int cnt = 0; do { cnt++; SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); fail = false; } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } //wrong username or password, get new one if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { fail = true; userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) {//the user is done return false; } // else //try again userName = userAndPass.get(0); password = userAndPass.get(1); } } finally { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } while (fail && cnt < 6); } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); //mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return false; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); ex.printStackTrace(); } if (fail) { return false; } //else return true; }
From source file:lucee.runtime.net.smtp.SMTPClient.java
private BodyPart toMimeBodyPart(MailPart part) throws MessagingException { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(/* www . ja va 2s . c o m*/ new DataHandler(new StringDataSource(part.getBody(), part.getType(), part.getCharset(), 980))); //mbp.setHeader("Content-Transfer-Encoding", "7bit"); //mbp.setHeader("Content-Type", TEXT_PLAIN+"; charset="+plainTextCharset); return mbp; }