List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart()
From source file:org.vosao.utils.EmailUtil.java
/** * Send email with html content and attachments. * @param htmlBody//w ww.jav a2s . 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())); 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:com.googlecode.ddom.mime.JavaMailTest.java
private void test(boolean preamble) throws Exception { MimeMultipart multipart = new MimeMultipart(); MimeBodyPart bodyPart1 = new MimeBodyPart(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 1000; i++) { buffer.append('('); buffer.append(i);//from w ww. j av a2s. c o m buffer.append(')'); } String content1 = buffer.toString(); bodyPart1 .setDataHandler(new DataHandler(new ByteArrayDataSource(content1.getBytes("UTF-8"), "text/plain"))); Map<String, String> headers1 = new HashMap<String, String>(); headers1.put("Content-ID", "<1@example.com>"); headers1.put("Content-Type", "text/plain; charset=UTF-8"); setHeaders(bodyPart1, headers1); multipart.addBodyPart(bodyPart1); MimeBodyPart bodyPart2 = new MimeBodyPart(); byte[] content2 = new byte[10000]; new Random().nextBytes(content2); bodyPart2.setDataHandler(new DataHandler(new ByteArrayDataSource(content2, "application/octet-stream"))); Map<String, String> headers2 = new HashMap<String, String>(); headers2.put("Content-ID", "<2@example.com>"); headers2.put("Content-Type", "application/octet-stream"); setHeaders(bodyPart2, headers2); multipart.addBodyPart(bodyPart2); if (preamble) { multipart.setPreamble("This is a MIME multipart."); } String boundary = new ContentType(multipart.getContentType()).getParameter("boundary"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); multipart.writeTo(baos); MultipartReader mpr = new MultipartReader(new ByteArrayInputStream(baos.toByteArray()), boundary); assertTrue(mpr.nextPart()); assertEquals(headers1, readHeaders(mpr)); assertEquals(content1, IOUtils.toString(mpr.getContent(), "UTF-8")); assertTrue(mpr.nextPart()); assertEquals(headers2, readHeaders(mpr)); assertArrayEquals(content2, IOUtils.toByteArray(mpr.getContent())); assertFalse(mpr.nextPart()); }
From source file:bo.com.offercruzmail.imp.FormadorMensajes.java
public static Multipart enviarErroresNegocio(BusinessException errores) throws MessagingException { Multipart cuerpo = new MimeMultipart(); StringBuilder mensaje = new StringBuilder(); if (errores instanceof PermisosInsuficientesException) { mensaje.append(errores.getMessage()); } else {/*from w ww . java 2s .c om*/ mensaje.append(escapeHtml4("No se pudo completar la peticin debido a los siguiente errores:")); mensaje.append("<br /><br />"); StringBuilder filas = new StringBuilder(); for (BusinessExceptionMessage error : errores.getMessages()) { if (error.getIndex() > 0) { filas.append(FormadorMensajes.envolverFilaExcepcion(error.getIndex() + "", escapeHtml4(error.getMessage()))); } else { filas.append(FormadorMensajes.envolverFilaExcepcion("-", escapeHtml4(error.getMessage()))); } } mensaje.append(FormadorMensajes.envolverTablaExcepcion(filas.toString())); } cuerpo.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(mensaje.toString())); return cuerpo; }
From source file:org.apache.usergrid.apm.service.util.Mailer.java
public static void send(String recipeintEmail, String subject, String messageText) { /*//from w ww.java2 s . com * It is a good practice to put this in a java.util.Properties file and * encrypt password. Scroll down to comments below to see how to use * java.util.Properties in JSF context. */ Properties props = new Properties(); try { props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/email.properties")); } catch (IOException e) { e.printStackTrace(); } final String senderEmail = props.getProperty("mail.smtp.sender.email"); final String smtpUser = props.getProperty("mail.smtp.user"); final String senderName = props.getProperty("mail.smtp.sender.name"); final String senderPassword = props.getProperty("senderPassword"); final String emailtoCC = props.getProperty("instaopsOpsEmailtoCC"); Session session = Session.getDefaultInstance(props, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUser, senderPassword); } }); session.setDebug(false); try { MimeMessage message = new MimeMessage(session); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(messageText, "text/html"); // Add message text Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); message.setSubject(subject); InternetAddress senderAddress = new InternetAddress(senderEmail, senderName); message.setFrom(senderAddress); message.addRecipient(Message.RecipientType.CC, new InternetAddress(emailtoCC)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipeintEmail)); Transport.send(message); log.info("email sent"); } catch (MessagingException m) { log.error(m.toString()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java
@Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { try {//from www .j a v a 2 s . c o m String from = null, to = null, subject = "", body = ""; // create a new multipart content MimeMultipart multiPart = new MimeMultipart(); for (FileItem item : sessionFiles) { if (item.isFormField()) { if ("from".equals(item.getFieldName())) from = item.getString(); if ("to".equals(item.getFieldName())) to = item.getString(); if ("subject".equals(item.getFieldName())) subject = item.getString(); if ("body".equals(item.getFieldName())) body = item.getString(); } else { // add the file part to multipart content MimeBodyPart part = new MimeBodyPart(); part.setFileName(item.getName()); part.setDataHandler( new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType()))); multiPart.addBodyPart(part); } } // add the text part to multipart content MimeBodyPart txtPart = new MimeBodyPart(); txtPart.setContent(body, "text/plain"); multiPart.addBodyPart(txtPart); // configure smtp server Properties props = System.getProperties(); props.put("mail.smtp.host", SMTP_SERVER); // create a new mail session and the mime message MimeMessage mime = new MimeMessage(Session.getInstance(props)); mime.setText(body); mime.setContent(multiPart); mime.setSubject(subject); mime.setFrom(new InternetAddress(from)); for (String rcpt : to.split("[\\s;,]+")) mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt)); // send the message Transport.send(mime); } catch (MessagingException e) { throw new UploadActionException(e.getMessage()); } return "Your mail has been sent successfuly."; }
From source file:net.sourceforge.vulcan.mailer.MessageAssembler.java
public MimeMessage constructMessage(String subscribers, ConfigDto config, ProjectStatusDto status, String html) throws MessagingException, AddressException { final MimeMessage message = new MimeMessage(mailSession); message.setSentDate(new Date()); message.setFrom(new InternetAddress(config.getSenderAddress())); if (isNotBlank(config.getReplyToAddress())) { message.setReplyTo(InternetAddress.parse(config.getReplyToAddress())); }//from w ww . j a v a2 s.co m message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(subscribers)); message.setSubject(status.getName() + ": " + status.getStatus()); final Multipart multipart = new MimeMultipart(); html = html.replaceAll("\\r", ""); addMultipartBody(multipart, "text/html; charset=UTF-8", html); message.setContent(multipart); return message; }
From source file:com.adaptris.util.text.mime.PartIteratorCase.java
protected static MimeMultipart createMultipart() throws Exception { MimeMultipart mime = new MimeMultipart(); try (BodyPartIterator bodies = new BodyPartIterator(generateByteArrayInput(false))) { while (bodies.hasNext()) { mime.addBodyPart(bodies.next()); }/*from ww w .j a v a 2 s. com*/ } ; return mime; }
From source file:servlets.mailPDF_Demo.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {// ww w .j av a 2 s . co m System.out.println("Reached @ mailPDF_Demo."); String pdfBase64 = request.getParameter("pdfBase64"); String reportdate = request.getParameter("reportdate"); String emailaddresses = request.getParameter("emailList"); String emailMessage = request.getParameter("emailMessage"); List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*")); System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End"); System.out.println(reportdate); System.out.println(emailaddresses); byte[] decodedBytes = decode(pdfBase64.substring(28)); MultiPartEmail email = new MultiPartEmail(); email.setSmtpPort(587); email.setDebug(false); email.setHostName("smtp.gmail.com"); email.setAuthentication("reporting@groupnp.com", "D3sign2015"); email.setTLS(true); for (String emailAddress : emailList) { email.addTo(emailAddress); } email.setFrom("reporting@groupnp.com"); email.setSubject("Yougov Tracker (" + reportdate + ")"); MimeMultipart part1 = new MimeMultipart(); BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8"); part1.addBodyPart(messageBodyPart1); email.addPart(part1); MimeMultipart part2 = new MimeMultipart(); BodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2 .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf"))); messageBodyPart2.removeHeader("Content-Transfer-Encoding"); messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64"); messageBodyPart2.setFileName("HCL_DemoTracker_" + reportdate + ".pdf"); part2.addBodyPart(messageBodyPart2); email.addPart(part2); email.send(); } catch (EmailException | MessagingException ex) { Logger.getLogger(mailPDF_Demo.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:servlets.mailPDF_Bronze_ACS.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//www. ja v a 2 s . c om System.out.println("Reached @ mailPDF_Bronze."); String pdfBase64 = request.getParameter("pdfBase64"); String reportdate = request.getParameter("reportdate"); String emailaddresses = request.getParameter("emailList"); String emailMessage = request.getParameter("emailMessage"); List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*")); System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End"); System.out.println(reportdate); System.out.println(emailaddresses); byte[] decodedBytes = decode(pdfBase64.substring(28)); MultiPartEmail email = new MultiPartEmail(); email.setSmtpPort(587); email.setDebug(false); email.setHostName("smtp.gmail.com"); email.setAuthentication("reporting@groupnp.com", "D3sign2015"); email.setTLS(true); for (String emailAddress : emailList) { email.addTo(emailAddress); } email.setFrom("reporting@groupnp.com"); email.setSubject("ACS Tracker (" + reportdate + ")"); MimeMultipart part1 = new MimeMultipart(); BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8"); part1.addBodyPart(messageBodyPart1); email.addPart(part1); MimeMultipart part2 = new MimeMultipart(); BodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2 .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf"))); messageBodyPart2.removeHeader("Content-Transfer-Encoding"); messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64"); messageBodyPart2.setFileName("ACSTracker_" + reportdate + ".pdf"); part2.addBodyPart(messageBodyPart2); email.addPart(part2); email.send(); } catch (EmailException | MessagingException ex) { Logger.getLogger(mailPDF_Bronze_ACS.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:servlets.mailPDF_Bronze_Temenos.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/* w ww . ja v a2 s . c om*/ System.out.println("Reached @ mailPDF_Bronze."); String pdfBase64 = request.getParameter("pdfBase64"); String reportdate = request.getParameter("reportdate"); String emailaddresses = request.getParameter("emailList"); String emailMessage = request.getParameter("emailMessage"); List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*")); System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End"); System.out.println(reportdate); System.out.println(emailaddresses); byte[] decodedBytes = decode(pdfBase64.substring(28)); MultiPartEmail email = new MultiPartEmail(); email.setSmtpPort(587); email.setDebug(false); email.setHostName("smtp.gmail.com"); email.setAuthentication("reporting@groupnp.com", "D3sign2015"); email.setTLS(true); for (String emailAddress : emailList) { email.addTo(emailAddress); } email.setFrom("reporting@groupnp.com"); email.setSubject("Temenos Tracker (" + reportdate + ")"); MimeMultipart part1 = new MimeMultipart(); BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8"); part1.addBodyPart(messageBodyPart1); email.addPart(part1); MimeMultipart part2 = new MimeMultipart(); BodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2 .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf"))); messageBodyPart2.removeHeader("Content-Transfer-Encoding"); messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64"); messageBodyPart2.setFileName("TemenosTracker_" + reportdate + ".pdf"); part2.addBodyPart(messageBodyPart2); email.addPart(part2); email.send(); } catch (EmailException | MessagingException ex) { Logger.getLogger(mailPDF_Bronze_Temenos.class.getName()).log(Level.SEVERE, null, ex); } }