List of usage examples for javax.mail.internet MimeBodyPart setContent
@Override public void setContent(Object o, String type) throws MessagingException
From source file:org.vosao.utils.EmailUtil.java
/** * Send email with html content and attachments. * @param htmlBody/*from w ww. j a v a 2 s. c o m*/ * @param subject * @param fromAddress * @param fromText * @param toAddress * @return null if OK or error message. */ public static String sendEmail(final String htmlBody, final String subject, final String fromAddress, final String fromText, final String toAddress, final List<FileItem> files) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try { Multipart mp = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlBody, "text/html"); htmlPart.setHeader("Content-type", "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); for (FileItem item : files) { MimeBodyPart attachment = new MimeBodyPart(); attachment.setFileName(item.getFilename()); String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename())); DataSource ds = new ByteArrayDataSource(item.getData(), mimeType); attachment.setDataHandler(new DataHandler(ds)); mp.addBodyPart(attachment); } MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress, fromText)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress)); msg.setSubject(subject, "UTF-8"); msg.setContent(mp); Transport.send(msg); return null; } catch (AddressException e) { return e.getMessage(); } catch (MessagingException e) { return e.getMessage(); } catch (UnsupportedEncodingException e) { return e.getMessage(); } }
From source file:org.vosao.utils.EmailUtil.java
/** * Send email with html content and attachments. * @param htmlBody/*w ww. java 2 s.co m*/ * @param subject * @param fromAddress * @param fromText * @param toAddress * @return null if OK or error message. */ public static String sendEmail(final String htmlBody, final String subject, final String fromAddress, final String fromText, final String toAddress, final List<FileItem> files) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try { Multipart mp = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlBody, "text/html"); htmlPart.setHeader("Content-type", "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); for (FileItem item : files) { MimeBodyPart attachment = new MimeBodyPart(); attachment.setFileName(item.getFilename()); String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename())); if (mimeType.equals("text/plain")) { mimeType = MimeType.DEFAULT; } DataSource ds = new ByteArrayDataSource(item.getData(), mimeType); attachment.setDataHandler(new DataHandler(ds)); mp.addBodyPart(attachment); } MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress, fromText)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress)); msg.setSubject(subject, "UTF-8"); msg.setContent(mp); Transport.send(msg); return null; } catch (AddressException e) { return e.getMessage(); } catch (MessagingException e) { return e.getMessage(); } catch (UnsupportedEncodingException e) { return e.getMessage(); } }
From source file:org.masukomi.aspirin.core.Bouncer.java
/** * This generates a response to the Return-Path address, or the address of * the message's sender if the Return-Path is not available. Note that this * is different than a mail-client's reply, which would use the Reply-To or * From header./*from ww w .jav a2 s . c om*/ * * @param mail * DOCUMENT ME! * @param message * DOCUMENT ME! * @param bouncer * DOCUMENT ME! * * @throws MessagingException * DOCUMENT ME! */ static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer) throws MessagingException { if (bouncer != null) { if (log.isDebugEnabled()) { log.debug("bouncing message to postmaster"); } MimeMessage orig = mail.getMessage(); //Create the reply message MimeMessage reply = (MimeMessage) orig.reply(false); //If there is a Return-Path header, if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) { //Return the message to that address, not to the Reply-To // address reply.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0])); } //Create the list of recipients in our MailAddress format Collection recipients = new HashSet(); Address[] addresses = reply.getAllRecipients(); for (int i = 0; i < addresses.length; i++) { recipients.add(new MailAddress((InternetAddress) addresses[i])); } //Change the sender... reply.setFrom(bouncer.toInternetAddress()); try { //Create the message body MimeMultipart multipart = new MimeMultipart(); //Add message as the first mime body part MimeBodyPart part = new MimeBodyPart(); part.setContent(message, "text/plain"); part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain"); multipart.addBodyPart(part); //Add the original message as the second mime body part part = new MimeBodyPart(); part.setContent(orig.getContent(), orig.getContentType()); part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType()); multipart.addBodyPart(part); reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date())); reply.setContent(multipart); reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType()); } catch (IOException ioe) { throw new MessagingException("Unable to create multipart body", ioe); } //Send it off... //sendMail( bouncer, recipients, reply ); que.queMail(reply); } }
From source file:com.pushinginertia.commons.net.email.EmailUtils.java
/** * Populates a newly instantiated {@link MultiPartEmail} with the given arguments. * @param email email instance to populate * @param smtpHost SMTP host that the message will be sent to * @param msg container object for the email's headers and contents * @throws IllegalArgumentException if the inputs are not valid * @throws EmailException if a problem occurs constructing the email *///from w w w .jav a 2 s . c o m public static void populateMultiPartEmail(final MultiPartEmail email, final String smtpHost, final EmailMessage msg) throws IllegalArgumentException, EmailException { ValidateAs.notNull(email, "email"); ValidateAs.notNull(smtpHost, "smtpHost"); ValidateAs.notNull(msg, "msg"); email.setHostName(smtpHost); email.setCharset(UTF_8); email.setFrom(msg.getSender().getEmail(), msg.getSender().getName(), UTF_8); email.addTo(msg.getRecipient().getEmail(), msg.getRecipient().getName(), UTF_8); final NameEmail replyTo = msg.getReplyTo(); if (replyTo != null) { email.addReplyTo(replyTo.getEmail(), replyTo.getName(), UTF_8); } final String bounceEmailAddress = msg.getBounceEmailAddress(); if (bounceEmailAddress != null) { email.setBounceAddress(bounceEmailAddress); } email.setSubject(msg.getSubject()); final String languageId = msg.getRecipient().getLanguage(); if (languageId != null) { email.addHeader("Language", languageId); email.addHeader("Content-Language", languageId); } // add optional headers final EmailMessageHeaders headers = msg.getHeaders(); if (headers != null) { for (final Map.Entry<String, String> header : headers.getHeaders().entrySet()) { email.addHeader(header.getKey(), header.getValue()); } } // generate email body try { final MimeMultipart mm = new MimeMultipart("alternative; charset=UTF-8"); final MimeBodyPart text = new MimeBodyPart(); text.setContent(msg.getTextContent(), "text/plain; charset=UTF-8"); mm.addBodyPart(text); final MimeBodyPart html = new MimeBodyPart(); html.setContent(msg.getHtmlContent(), "text/html; charset=UTF-8"); mm.addBodyPart(html); email.setContent(mm); } catch (MessagingException e) { throw new EmailException(e); } }
From source file:org.openmrs.module.sync.SyncMailUtil.java
/** * Sends a message using the current mail session *//* w w w. j a va 2s. co m*/ public static void sendMessage(String recipients, String subject, String body) throws MessageException { try { Message message = new MimeMessage(getMailSession()); message.setSentDate(new Date()); if (StringUtils.isNotBlank(subject)) { message.setSubject(subject); } if (StringUtils.isNotBlank(recipients)) { for (String recipient : recipients.split("\\,")) { message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipient)); } } if (StringUtils.isNotBlank(body)) { Multipart multipart = new MimeMultipart(); MimeBodyPart contentBodyPart = new MimeBodyPart(); contentBodyPart.setContent(body, "text/html"); multipart.addBodyPart(contentBodyPart); message.setContent(multipart); } log.info("Sending email with subject <" + subject + "> to <" + recipients + ">"); log.debug("Mail has contents: \n" + body); Transport.send(message); log.debug("Message sent without errors"); } catch (Exception e) { log.error("Message could not be sent due to " + e.getMessage(), e); throw new MessageException(e); } }
From source file:com.medsavant.mailer.Mail.java
public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) { try {/*from ww w . jav a 2 s . c om*/ if (src == null || pw == null || host == null || port == -1) { return false; } if (to.isEmpty()) { return false; } LOG.info("Sending email to " + to + " with subject " + subject); // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.user", src); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.starttls.enable", starttls); props.put("mail.smtp.auth", auth); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", socketFactoryClass); props.put("mail.smtp.socketFactory.fallback", fallback); Session session = Session.getInstance(props, null); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(src, srcName)); InternetAddress[] address = InternetAddress.parse(to); msg.setRecipients(Message.RecipientType.BCC, address); msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(text, "text/html"); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); if (attachment != null) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); mp.addBodyPart(mbp2); } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // send the message Transport transport = session.getTransport("smtp"); transport.connect(host, src, pw); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); LOG.info("Mail sent"); return true; } catch (Exception ex) { ex.printStackTrace(); LOG.error(ex); return false; } }
From source file:com.email.SendEmailCalInvite.java
/** * Builds the body for the email// w w w. ja v a 2 s . co m * * @param eml EmailOutInvitesModel * @return String (Body) */ private static BodyPart body(EmailOutInvitesModel eml) { MimeBodyPart descriptionPart = new MimeBodyPart(); try { String content = eml.getEmailBody() + "\n\n\n"; descriptionPart.setContent(content, "text/html; charset=utf-8"); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } return descriptionPart; }
From source file:com.sat.common.CustomReport.java
/** * Sendmail.//from w ww . j av a2 s . c om * * @param msg * the msg * @throws AddressException * the address exception * @throws IOException * Signals that an I/O exception has occurred. */ public static void sendmail(String msg) throws AddressException, IOException { ConfigFileHandlerManager miscConfigFileHandlerManager = new ConfigFileHandlerManager(); miscConfigFileHandlerManager.loadPropertiesBasedonPropertyFileName("com.cisco.lms.lms"); Validate miscValidate = new Validate(); String from = miscValidate.readsystemvariable("MAIL.FROM"); String host = miscValidate.readsystemvariable("MAIL.SMTP.HOST"); String to = miscValidate.readsystemvariable("MAIL.TO"); String subject = miscValidate.readsystemvariable("MAIL.SUBJECT"); String personal = miscValidate.readsystemvariable("MAIL.FROM.PERSONAL"); // Mail to details Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); // compose the message try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from, personal)); message.addRecipients(Message.RecipientType.TO, to); message.setSubject(subject); Multipart mp = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(msg, "text/html"); mp.addBodyPart(htmlPart); message.setContent(mp); Transport.send(message); System.out.println(msg); System.out.println("message sent successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } catch (Exception e) { System.out.println("\tException in sending mail to configured mailers list"); } }
From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java
/** * Opens the IMAP folder, deletes all messages which match the magic subject and * creates a new message with an attachment which contains the object serialized *//*from w w w.j av a 2 s . co m*/ protected static void saveUserPreferencesInIMAP(Log logger, User user, Session session, IMAPStore iStore, String folderName, String subject, Object object) throws MessagingException, IOException, InterruptedException { IMAPFolder folder = (IMAPFolder) iStore.getFolder(folderName); if (folder.exists() || folder.create(IMAPFolder.HOLDS_MESSAGES)) { if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } // Serialize the object ByteArrayOutputStream fout = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(object); oos.close(); ByteArrayInputStream is = new ByteArrayInputStream(fout.toByteArray()); // Create a new message with an attachment which has the serialized object MimeMessage message = new MimeMessage(session); message.setSubject(subject); Multipart multipart = new MimeMultipart(); MimeBodyPart txtPart = new MimeBodyPart(); txtPart.setContent("This message contains configuration used by Hupa, do not delete it", "text/plain"); multipart.addBodyPart(txtPart); FileItem item = createPreferencesFileItem(is, subject, HUPA_DATA_MIME_TYPE); multipart.addBodyPart(MessageUtils.fileitemToBodypart(item)); message.setContent(multipart); message.saveChanges(); // It seems it's not possible to modify the content of an existing message using the API // So I delete the previous message storing the preferences and I create a new one Message[] msgs = folder.getMessages(); for (Message msg : msgs) { if (subject.equals(msg.getSubject())) { msg.setFlag(Flag.DELETED, true); } } // It is necessary to copy the message before saving it (the same problem in AbstractSendMessageHandler) message = new MimeMessage((MimeMessage) message); message.setFlag(Flag.SEEN, true); folder.appendMessages(new Message[] { message }); folder.close(true); logger.info("Saved preferences " + subject + " in imap folder " + folderName + " for user " + user); } else { logger.error("Unable to save preferences " + subject + " in imap folder " + folderName + " for user " + user); } }
From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java
/** * Helper function to create multi-part MIME * * @param entity the body of a request * @param entityContentType content type of the body * @param query a query part of a request * * @return a ByteString that represents a multi-part encoded entity that contains both *///from w ww . j ava2s . c o m private static MimeMultipart createMultiPartEntity(ByteString entity, String entityContentType, String query) throws MessagingException { MimeMultipart multi = new MimeMultipart(MIXED); // Create current entity with the associated type MimeBodyPart dataPart = new MimeBodyPart(); ContentType contentType = new ContentType(entityContentType); dataPart.setContent(entity.copyBytes(), contentType.getBaseType()); dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType); // Encode query params as form-urlencoded MimeBodyPart argPart = new MimeBodyPart(); argPart.setContent(query, FORM_URL_ENCODED); argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); multi.addBodyPart(argPart); multi.addBodyPart(dataPart); return multi; }