List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart()
From source file:org.openmrs.module.sync.SyncMailUtil.java
/** * Sends a message using the current mail session *///from www . j av a 2 s.c o 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 {// ww w.java2s . 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:org.apache.james.transport.mailets.StripAttachmentTest.java
@Test public void testSimpleAttachment2() throws MessagingException, IOException { Mailet mailet = new StripAttachment(); FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext()); mci.setProperty("directory", "./"); mci.setProperty("remove", "all"); mci.setProperty("notpattern", "^(winmail\\.dat$)"); mailet.init(mci);//from www . j a va 2 s .com MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMultipart mm = new MimeMultipart(); MimeBodyPart mp = new MimeBodyPart(); mp.setText("simple text"); mm.addBodyPart(mp); String body = "\u0023\u00A4\u00E3\u00E0\u00E9"; MimeBodyPart mp2 = new MimeBodyPart( new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body).getBytes("UTF-8"))); mp2.setDisposition("attachment"); mp2.setFileName("temp.tmp"); mm.addBodyPart(mp2); String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4"; MimeBodyPart mp3 = new MimeBodyPart( new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body2).getBytes("UTF-8"))); mp3.setDisposition("attachment"); mp3.setFileName("winmail.dat"); mm.addBodyPart(mp3); message.setSubject("test"); message.setContent(mm); message.saveChanges(); Mail mail = FakeMail.builder().mimeMessage(message).build(); mailet.service(mail); ByteArrayOutputStream rawMessage = new ByteArrayOutputStream(); mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" }); // String res = rawMessage.toString(); @SuppressWarnings("unchecked") Collection<String> c = (Collection<String>) mail .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY); Assert.assertNotNull(c); Assert.assertEquals(1, c.size()); String name = c.iterator().next(); File f = new File("./" + name); try { InputStream is = new FileInputStream(f); String savedFile = toString(is); is.close(); Assert.assertEquals(body, savedFile); } finally { FileUtils.deleteQuietly(f); } }
From source file:de.elomagic.mag.AbstractTest.java
protected MimeMessage createMimeMessage(String filename) throws Exception { MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent("This is some text to be displayed inline", "text/plain"); textPart.setDisposition(Part.INLINE); MimeBodyPart binaryPart = new MimeBodyPart(); InputStream in = getClass().getResourceAsStream("/TestFile.pdf"); binaryPart.setContent(getOriginalMailAttachment(), "application/pdf"); binaryPart.setDisposition(Part.ATTACHMENT); binaryPart.setFileName(filename);/*from w w w. j av a 2s . c o m*/ Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(binaryPart); MimeMessage message = new MimeMessage(greenMail.getImap().createSession()); message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("mailuser@localhost.com") }); message.setSubject("Another test mail subject"); message.setContent(mp); // return message; // GreenMailUtil.createTextEmail("to@localhost.com", "from@localhost.com", "subject", "body", greenMail.getImap().getServerSetup()); }
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 a2 s .c om*/ 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:net.sf.jclal.util.mail.SenderEmail.java
/** * Send the email with the indicated parameters * * @param subject The subject/* w w w . j a v a 2 s. c o m*/ * @param content The content * @param reportFile The reportFile to send */ public void sendEmail(String subject, String content, File reportFile) { // Get system properties Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); if (!user.isEmpty() && !pass.isEmpty()) { properties.setProperty("mail.user", user); properties.setProperty("mail.password", pass); } // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipients(Message.RecipientType.TO, toRecipients.toString()); // Set Subject: header field message.setSubject(subject); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText(content); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); if (attachReporFile) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile))); messageBodyPart.setFileName(reportFile.getName()); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e); } }
From source file:bo.com.offercruzmail.imp.FormadorMensajes.java
public static Multipart getMensajeUsuarioAyuda(boolean comandoReconocido) throws MessagingException { Multipart multiPartes = new MimeMultipart(); StringBuilder mensaje = new StringBuilder(); if (comandoReconocido) { //Es ayuda mensaje.append("Manual de comandos para el sistema de lector de bandeja Kibo. <br /><br />"); } else {/*w w w.j a va 2 s . c o m*/ mensaje.append(escapeHtml4( "El mensaje no ha sido reconocido, consulte el manual para enviar un mensaje vlido.")); mensaje.append("<br /><br />"); } mensaje.append(FormadorMensajes.tablaHtmlAyuda); multiPartes.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(mensaje.toString())); return multiPartes; }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
/** * Prepares a plain MimeMessage: the MimeMessage.RecipientType.TO is not yet set * @return//from ww w. j a va2 s .c o m * @throws Exception */ private MimeMessage preparePlainMimeMessage(InternetAddress internetAddressFrom, String subject, String plainBody, List<LabelValueBean> attachments) throws Exception { MimeMessage msg = new MimeMessage(session); msg.setFrom(internetAddressFrom); msg.setHeader(XMAILER, xmailer); msg.setSubject(subject.trim(), mailEncoding); msg.setSentDate(new Date()); if (attachments == null || attachments.isEmpty()) { msg.setText(plainBody, mailEncoding); } else { MimeMultipart mimeMultipart = new MimeMultipart(); MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText(plainBody, mailEncoding); mimeMultipart.addBodyPart(textBodyPart); if (attachments != null) { includeAttachments(mimeMultipart, attachments); } msg.setContent(mimeMultipart); } return msg; }
From source file:com.reizes.shiva.net.mail.Mail.java
public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject, String content) throws UnsupportedEncodingException, MessagingException { boolean parseStrict = false; MimeMessage message = new MimeMessage(getSessoin()); InternetAddress address = InternetAddress.parse(from, parseStrict)[0]; if (fromName != null) { address.setPersonal(fromName, charset); }//from w ww.ja v a 2s .c o m message.setFrom(address); message.setRecipients(Message.RecipientType.TO, parseAddresses(to)); if (cc != null) { message.setRecipients(Message.RecipientType.CC, parseAddresses(cc)); } if (bcc != null) { message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc)); } message.setSubject(subject, charset); message.setHeader("X-Mailer", "sendMessage"); message.setSentDate(new java.util.Date()); // Multipart multipart = new MimeMultipart(); MimeBodyPart bodypart = new MimeBodyPart(); bodypart.setContent(content, "text/html; charset=" + charset); multipart.addBodyPart(bodypart); message.setContent(multipart); Transport.send(message); }
From source file:org.latticesoft.util.resource.MessageUtil.java
/** * Sends the email./* w w w.j av a2 s .com*/ * @param info the EmailInfo containing the message and other details * @param p the properties to set in the environment when instantiating the session * @param auth the authenticator */ public static void sendMail(EmailInfo info, Properties p, Authenticator auth) { try { if (p == null) { if (log.isErrorEnabled()) { log.error("Null properties!"); } return; } Session session = Session.getInstance(p, auth); session.setDebug(true); if (log.isInfoEnabled()) { log.info(p); log.info(session); } MimeMessage mimeMessage = new MimeMessage(session); if (log.isInfoEnabled()) { log.info(mimeMessage); log.info(info.getFromAddress()); } mimeMessage.setFrom(info.getFromAddress()); mimeMessage.setSentDate(new Date()); List l = info.getToList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); if (log.isInfoEnabled()) { log.info(addr); } mimeMessage.addRecipients(Message.RecipientType.TO, addr); } } l = info.getCcList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.CC, addr); } } l = info.getBccList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.BCC, addr); } } if (info.getAttachment().size() == 0) { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); mimeMessage.setText(info.getContent(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); mimeMessage.setText(info.getContent()); } mimeMessage.setContent(info.getContent(), info.getContentType()); } else { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); } Multipart mp = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); if (info.getCharSet() != null) { body.setText(info.getContent(), info.getCharSet()); body.setContent(info.getContent(), info.getContentType()); } else { body.setText(info.getContent()); body.setContent(info.getContent(), info.getContentType()); } mp.addBodyPart(body); for (int i = 0; i < info.getAttachment().size(); i++) { String filename = (String) info.getAttachment().get(i); MimeBodyPart attachment = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); attachment.setDataHandler(new DataHandler(fds)); attachment.setFileName(MimeUtility.encodeWord(fds.getName())); mp.addBodyPart(attachment); } mimeMessage.setContent(mp); } Transport.send(mimeMessage); } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Error in sending email", e); } } }