List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:SendMime.java
/** Do the work: send the mail to the SMTP server. */ public void doSend() throws IOException, MessagingException { // Create the Session object session = Session.getDefaultInstance(null, null); session.setDebug(true); // Verbose! try {/*from ww w.j ava2 s. c o m*/ // create a message mesg = new MimeMessage(session); // From Address - this should come from a Properties... mesg.setFrom(new InternetAddress("nobody@host.domain")); // TO Address InternetAddress toAddress = new InternetAddress(message_recip); mesg.addRecipient(Message.RecipientType.TO, toAddress); // CC Address InternetAddress ccAddress = new InternetAddress(message_cc); mesg.addRecipient(Message.RecipientType.CC, ccAddress); // The Subject mesg.setSubject(message_subject); // Now the message body. Multipart mp = new MimeMultipart(); BodyPart textPart = new MimeBodyPart(); textPart.setText(message_body); // sets type to "text/plain" BodyPart pixPart = new MimeBodyPart(); pixPart.setContent(html_data, "text/html"); // Collect the Parts into the MultiPart mp.addBodyPart(textPart); mp.addBodyPart(pixPart); // Put the MultiPart into the Message mesg.setContent(mp); // Finally, send the message! Transport.send(mesg); } catch (MessagingException ex) { System.err.println(ex); ex.printStackTrace(System.err); } }
From source file:com.mylab.mail.OpenCmsMailService.java
public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException { log.debug("Sending multipart message " + config); Session session = getSession();//from w w w . j a v a2 s .c o m MimeMultipart multipart = new MimeMultipart(); MimeBodyPart html = new MimeBodyPart(); html.setContent(config.getContent(), config.getContentType()); html.setHeader("MIME-Version", "1.0"); html.setHeader("Content-Type", html.getContentType()); multipart.addBodyPart(html); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(ds)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); final MimeMessage message = new MimeMessage(session); message.setContent(multipart); try { message.setFrom(new InternetAddress(config.getFrom(), config.getFromName())); addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig()); } catch (UnsupportedEncodingException ex) { throw new MessagingException("Setting from or to failed", ex); } message.setSubject(config.getSubject()); // we don't send in a new Thread so that we get the Exception Transport.send(message); }
From source file:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java
/** Send mail in HTML format */ private boolean sendHtmlMail(MailSenderInfo mailInfo) { boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable"); if (enableMailAlert) { SaAuthenticatorInfo authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword()); }// w ww . ja v a 2 s .c o m Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { Message mailMessage = new MimeMessage(sendMailSession); Address from = new InternetAddress(mailInfo.getFromAddress()); mailMessage.setFrom(from); Address[] to = new Address[mailInfo.getToAddress().split(",").length]; int i = 0; for (String e : mailInfo.getToAddress().split(",")) to[i++] = new InternetAddress(e); mailMessage.setRecipients(Message.RecipientType.TO, to); mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSentDate(new Date()); Multipart mainPart = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8"); mainPart.addBodyPart(html); if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) { for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) { MimeBodyPart mbp = new MimeBodyPart(); File file = new File(entry.getValue()); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); try { mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null)); } catch (Exception e) { e.printStackTrace(); } mbp.setContentID(entry.getKey()); mbp.setHeader("Content-ID", "<image>"); mainPart.addBodyPart(mbp); } } List<File> list = mailInfo.getFileList(); if (list != null && list.size() > 0) { for (File f : list) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f.getAbsolutePath()); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(f.getName()); mainPart.addBodyPart(mbp); } list.clear(); } mailMessage.setContent(mainPart); // mailMessage.saveChanges(); Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } } return false; }
From source file:nl.surfnet.coin.teams.util.ControllerUtilImpl.java
@Override public MimeMultipart getMimeMultipartMessageBody(String plainText, String html) throws MessagingException { MimeMultipart multiPart = new MimeMultipart("alternative"); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(plainText, "utf-8"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html; charset=utf-8"); multiPart.addBodyPart(textPart); // least important multiPart.addBodyPart(htmlPart); // most important return multiPart; }
From source file:com.emc.plants.service.impl.MailerBean.java
/** * Create a mail message and send it./* www .j a v a 2 s . c o m*/ * * @param customerInfo Customer information. * @param orderKey * @throws MailerAppException */ public void createAndSendMail(CustomerInfo customerInfo, long orderKey) throws MailerAppException { try { EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey), customerInfo.getCustomerID()); Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: " + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents()); //Session mailSession = (Session) Util.getInitialContext().lookup(MAIL_SESSION); MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false)); msg.setSubject(eMessage.getSubject()); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(eMessage.getHtmlContents(), "us-ascii"); msg.setHeader("X-Mailer", "JavaMailer"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp); msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); Util.debug("\nMail sent successfully."); } catch (Exception e) { Util.debug("Error sending mail. Have mail resources been configured correctly?"); Util.debug("createAndSendMail exception : " + e); e.printStackTrace(); throw new MailerAppException("Failure while sending mail"); } }
From source file:com.jwm123.loggly.reporter.ReportMailer.java
public MimeBodyPart newTextBodyPart(String text) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(text, "text/plain; charset=UTF-8"); return mimeBodyPart; }
From source file:org.wf.dp.dniprorada.util.Mail.java
public Mail _Attach(DataSource oDataSource, String sFileName, String sDescription) { try {// w ww. java 2s .c o m MimeBodyPart oMimeBodyPart = new MimeBodyPart(); oMimeBodyPart.setHeader("Content-Type", "multipart/mixed"); oMimeBodyPart.setDataHandler(new DataHandler(oDataSource)); oMimeBodyPart.setFileName(MimeUtility.encodeText(sFileName)); oMultiparts.addBodyPart(oMimeBodyPart); log.info("[_Attach:oFile]:sFileName=" + sFileName + ",sDescription=" + sDescription); } catch (Exception oException) { log.error("[_Attach:oFile]sFileName=" + sFileName + ",sDescription=" + sDescription, oException); } return this; }
From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java
@Override protected void executeImpl(Action action, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) { // Get the email properties entered via Share Form String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME); String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME); String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME); // Get document filename Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef, ContentModel.PROP_NAME); if (filename == null) { throw new AlfrescoRuntimeException("Document filename is null"); }//from ww w .j ava 2 s. co m String documentName = (String) filename; try { // Create mail session Properties mailServerProperties = new Properties(); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.host", "localhost"); mailServerProperties.put("mail.smtp.port", "2525"); Session session = Session.getDefaultInstance(mailServerProperties, null); session.setDebug(false); // Define message Message message = new MimeMessage(session); String fromAddress = "training@alfresco.com"; message.setFrom(new InternetAddress(fromAddress)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); // Create the message part with body text BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create the Attachment part // // Get the document content bytes byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName); if (documentData == null) { throw new AlfrescoRuntimeException("Document content is null"); } // Attach document messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData, new MimetypesFileTypeMap().getContentType(documentName)))); messageBodyPart.setFileName(documentName); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send mail Transport.send(message); // Set status on node as "sent via email" Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); properties.put(ContentModel.PROP_ORIGINATOR, fromAddress); properties.put(ContentModel.PROP_ADDRESSEE, to); properties.put(ContentModel.PROP_SUBJECT, subject); properties.put(ContentModel.PROP_SENTDATE, new Date()); serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED, properties); } catch (MessagingException me) { me.printStackTrace(); throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage()); } } }
From source file:it.cnr.icar.eric.common.RepositoryItemImpl.java
/** * Packages the RepositoryItem as a MimeMultiPart and returns it * * @deprecated sigElement/multipart attachment is not used anymore. *///from w ww .j a v a 2s . com public MimeMultipart getMimeMultipart() throws RegistryException { MimeMultipart mp = null; try { //Create a multipart with two bodyparts //First bodypart is an XMLDSIG and second is the attached file mp = new MimeMultipart(); //The signature part ByteArrayOutputStream os = new ByteArrayOutputStream(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(sigElement), new StreamResult(os)); MimeBodyPart bp1 = new MimeBodyPart(); bp1.addHeader("Content-ID", "payload1"); bp1.setText(os.toString(), "utf-8"); mp.addBodyPart(bp1); //The payload part MimeBodyPart bp2 = new MimeBodyPart(); bp2.setDataHandler(handler); bp2.addHeader("Content-Type", handler.getContentType()); bp2.addHeader("Content-ID", "payload2"); mp.addBodyPart(bp2); } catch (MessagingException e) { throw new RegistryException(e); } catch (TransformerException e) { throw new RegistryException(e); } return mp; }
From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapterTest.java
@Test public void testCorruptMessage() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); Mailet mailet = new BlackberrySMIMEAdapter(); String template = FileUtils.readFileToString(new File("resources/templates/blackberry-smime-adapter.ftl")); autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template); mailetConfig.setInitParameter("log", "starting"); /* use some dummy template because we must specify the default template */ mailetConfig.setInitParameter("template", "sms.ftl"); mailetConfig.setInitParameter("templateProperty", "pdfTemplate"); mailet.init(mailetConfig);/*from w w w .j a v a 2 s. co m*/ MockMail mail = new MockMail(); mail.setState(Mail.DEFAULT); MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); MimeBodyPart emptyPart = new MimeBodyPart(); message.setContent(emptyPart, "text/plain"); message.saveChanges(); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("123@EXAMPLE.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("sender@example.com")); mailet.service(mail); assertEquals(message, mail.getMessage()); try { MailUtils.validateMessage(message); fail(); } catch (IOException e) { // expected. The message should be corrupt } }