List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart()
From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java
public static void SendEmailSephoraFailed(String adresaSephora, String from, String to1, String to2, String grupSephora, String subject, String filename) throws FileNotFoundException, IOException { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); //get Session Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, "anda.cristea"); }//from w w w. ja va2 s . c o m }); //compose message try { MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1)); message.setSubject(subject); // message.setText(msg); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Raport teste automate"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); //send message Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:org.etudes.jforum.util.mail.Spammer.java
/** * prepare attachment message/*from www . j a v a2 s . co m*/ * @param addresses Addresses * @param params Message params * @param subject Message subject * @param messageFile Message file * @param attachments Attachments * @throws EmailException */ protected final void prepareAttachmentMessage(List addresses, SimpleHash params, String subject, String messageFile, List attachments) throws EmailException { if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments entering....."); this.message = new MimeMessage(session); try { InternetAddress[] recipients = new InternetAddress[addresses.size()]; String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET); this.message.setSentDate(new Date()); // this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER))); String from = "\"" + ServerConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@" + ServerConfigurationService.getServerName() + ">"; this.message.setFrom(new InternetAddress(from)); this.message.setSubject(subject, charset); this.messageText = this.getMessageText(params, messageFile); MimeBodyPart messageBodyPart = new MimeBodyPart(); String messagetype = ""; // message if (messageFormat == MESSAGE_HTML) { messagetype = "text/html; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } else { messagetype = "text/plain; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // attachments Attachment attachment = null; Iterator iterAttach = attachments.iterator(); while (iterAttach.hasNext()) { attachment = (Attachment) iterAttach.next(); // String filePath = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); String filePath = SakaiSystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); try { messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getInfo().getRealFilename()); multipart.addBodyPart(messageBodyPart); } catch (MessagingException e) { if (logger.isWarnEnabled()) logger.warn("Error while attaching attachments in prepareAttachmentMessage(...) : " + e); } } message.setContent(multipart); int i = 0; for (Iterator iter = addresses.iterator(); iter.hasNext(); i++) { recipients[i] = new InternetAddress((String) iter.next()); } this.message.setRecipients(Message.RecipientType.TO, recipients); } catch (Exception e) { logger.warn(e); throw new EmailException(e); } if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments exiting....."); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailHtmlTextWithAttachment() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Html Email test with attachment"); String html = loadHtml();//from ww w . j a va 2s.c om MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.ATTACHMENT); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setContent(html, "text/html; charset=\"UTF-8\""); Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Html Email test with attachment", message.getTitle()); assertEquals(html, message.getBody()); assertEquals(htmlEmailSummary, message.getSummary()); assertEquals(ATT_SIZE, message.getAttachmentsSize()); assertEquals(1, message.getAttachments().size()); String path = MessageFormat.format(attachmentPath, messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId())); Attachment attached = message.getAttachments().iterator().next(); assertEquals(path, attached.getPath()); assertEquals("lemonde.html", attached.getFileName()); assertEquals("componentId", message.getComponentId()); assertEquals("text/html", message.getContentType()); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); }
From source file:org.silverpeas.core.mail.SmtpMailSendingTest.java
@Test public void sendingMailSynchronouslyValidMailWithReplyTo(GreenMailOperations mail) throws Exception { MailAddress senderEmail = MailAddress.eMail(COMMON_FROM).withName("From Personal Name"); MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name"); String subject = "A subject"; Multipart content = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE); content.addBodyPart(mimeBodyPart);//from ww w . j ava2s .c o m MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject) .withContent(content).setReplyToRequired(); // Sending mail mailSending.sendSynchronously(); // Verifying sent data MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend; assertThat(mailToSend.getFrom(), is(senderEmail)); assertThat(mailToSend.getTo(), hasItem(receiverEmail)); assertThat(mailToSend.getSubject(), is(subject)); assertThat(mailToSend.getContent().isHtml(), is(true)); assertThat(mailToSend.getContent().toString(), is(content.toString())); assertThat(mailToSend.isReplyToRequired(), is(true)); assertThat(mailToSend.isAsynchronous(), is(false)); assertMailSent(mailToSend, mail); }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail.//from w w w. ja v a 2s . c o m * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:org.apache.nifi.processors.standard.PutEmail.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final FlowFile flowFile = session.get(); if (flowFile == null) { return;//from www . ja v a2 s . co m } final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile); final Session mailSession = this.createMailSession(properties); final Message message = new MimeMessage(mailSession); final ComponentLog logger = getLogger(); try { message.addFrom(toInetAddresses(context, flowFile, FROM)); message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO)); message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC)); message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC)); message.setHeader("X-Mailer", context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue()); message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue()); String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue(); if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) { messageText = formatAttributes(flowFile, messageText); } String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile) .getValue(); message.setContent(messageText, contentType); message.setSentDate(new Date()); if (context.getProperty(ATTACH_FILE).asBoolean()) { final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64"); mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource( Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\""))); final MimeBodyPart mimeFile = new MimeBodyPart(); session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream stream) throws IOException { try { mimeFile.setDataHandler( new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream"))); } catch (final Exception e) { throw new IOException(e); } } }); mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key())); MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeText); multipart.addBodyPart(mimeFile); message.setContent(multipart); } send(message); session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString()); session.transfer(flowFile, REL_SUCCESS); logger.info("Sent email as a result of receiving {}", new Object[] { flowFile }); } catch (final ProcessException | MessagingException | IOException e) { context.yield(); logger.error("Failed to send email for {}: {}; routing to failure", new Object[] { flowFile, e.getMessage() }, e); session.transfer(flowFile, REL_FAILURE); } }
From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java
/** * Deliver the original mail as an attachment with the main part being an error report. * * @param recipient/*from w ww. ja va2s. c om*/ * @param aMail * @param ex * @throws MessagingException * @throws IOException */ protected void handleFailure(MailAddress recipient, Mail aMail, Exception ex) throws MessagingException, IOException { String user = getUsername(recipient); MimeMessage originalMessage = aMail.getMessage(); MimeMessage message = new MimeMessage(originalMessage); MimeMultipart multipart = new MimeMultipart(); MimeBodyPart noticePart = new MimeBodyPart(); noticePart.setText(new StringBuilder().append( "An error was encountered while processing this mail with the active sieve script for user \"") .append(user).append("\". The error encountered was:\r\n").append(ex.getLocalizedMessage()) .append("\r\n").toString()); multipart.addBodyPart(noticePart); MimeBodyPart originalPart = new MimeBodyPart(); originalPart.setContent(originalMessage, "message/rfc822"); if ((originalMessage.getSubject() != null) && (!originalMessage.getSubject().trim().isEmpty())) { originalPart.setFileName(originalMessage.getSubject().trim()); } else { originalPart.setFileName("No Subject"); } originalPart.setDisposition(MimeBodyPart.INLINE); multipart.addBodyPart(originalPart); message.setContent(multipart); message.setSubject("[SIEVE ERROR] " + originalMessage.getSubject()); message.setHeader("X-Priority", "1"); message.saveChanges(); storeMessageInbox(user, message); }
From source file:com.openkm.util.MailUtils.java
/** * Create a mail.// ww w . j av a 2 s. c o m * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null && Config.SEND_MAIL_FROM_USER) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:com.gtwm.jasperexecute.RunJasperReports.java
public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException { Properties props = new Properties(); //props.setProperty("mail.debug", "true"); props.setProperty("mail.smtp.host", emailHost); if (emailUser != null) { props.setProperty("mail.smtp.auth", "true"); }// ww w .jav a2 s . c om Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass); Session mailSession = Session.getDefaultInstance(props, emailAuthenticator); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); // transport.connect(emailHost, emailUser, emailPass); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:com.sat.common.CustomReport.java
/** * Sendmail.//from ww w . j a v a 2 s . c o m * * @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"); } }