List of usage examples for javax.mail Multipart addBodyPart
public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:org.apache.axis2.transport.mail.EMailSender.java
private void createMailMimeMessage(final MimeMessage msg, MailToInfo mailToInfo, OMOutputFormat format) throws MessagingException { // Create the message part BodyPart messageBodyPart = new MimeBase64BodyPart(); messageBodyPart.setText(""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); DataSource source = null;/*from w w w.j a v a 2s . com*/ // Part two is attachment if (outputStream instanceof ByteArrayOutputStream) { source = new ByteArrayDataSource(((ByteArrayOutputStream) outputStream).toByteArray()); } messageBodyPart = new MimeBase64BodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setDisposition(Part.ATTACHMENT); messageBodyPart.addHeader("Content-Description", "\"" + mailToInfo.getContentDescription() + "\""); String contentType = format.getContentType() != null ? format.getContentType() : Constants.DEFAULT_CONTENT_TYPE; if (contentType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) { if (messageContext.getSoapAction() != null) { messageBodyPart.setHeader(Constants.HEADER_SOAP_ACTION, messageContext.getSoapAction()); } } if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) { if (messageContext.getSoapAction() != null) { messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding() + " ; action=\"" + messageContext.getSoapAction() + "\""); } } else { messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding()); } multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); }
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); }/* w w w. j av a 2s.co 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.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()); }/*from w ww .j av a 2 s . co 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:org.eclipse.che.mail.MailSender.java
public void sendMail(EmailBean emailBean) throws SendMailException { File tempDir = null;/* w ww . j a v a 2s. c o m*/ try { MimeMessage message = new MimeMessage(mailSessionProvider.get()); Multipart contentPart = new MimeMultipart(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType())); contentPart.addBodyPart(bodyPart); if (emailBean.getAttachments() != null) { tempDir = Files.createTempDir(); for (Attachment attachment : emailBean.getAttachments()) { // Create attachment file in temporary directory byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent()); File attachmentFile = new File(tempDir, attachment.getFileName()); Files.write(attachmentContent, attachmentFile); // Attach the attachment file to email MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(attachmentFile); attachmentPart.setContentID("<" + attachment.getContentId() + ">"); contentPart.addBodyPart(attachmentPart); } } message.setContent(contentPart); message.setSubject(emailBean.getSubject(), "UTF-8"); message.setFrom(new InternetAddress(emailBean.getFrom(), true)); message.setSentDate(new Date()); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo())); if (emailBean.getReplyTo() != null) { message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo())); } LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(), emailBean.getSubject()); Transport.send(message); LOG.debug("Mail sent"); } catch (Exception e) { LOG.error(e.getLocalizedMessage()); throw new SendMailException(e.getLocalizedMessage(), e); } finally { if (tempDir != null) { try { FileUtils.deleteDirectory(tempDir); } catch (IOException exception) { LOG.error(exception.getMessage()); } } } }
From source file:io.mapzone.arena.share.app.EMailSharelet.java
private void sendEmail(final String toText, final String subjectText, final String messageText, final boolean withAttachment, final ImagePngContent image) throws Exception { MimeMessage msg = new MimeMessage(mailSession()); msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false)); // TODO we need the FROM from the current user msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setSubject(subjectText, "utf-8"); if (withAttachment) { // add mime multiparts Multipart multipart = new MimeMultipart(); BodyPart part = new MimeBodyPart(); part.setText(messageText);/*from w w w .j a v a 2s . c o m*/ multipart.addBodyPart(part); // Second part is attachment part = new MimeBodyPart(); part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource)))); part.setFileName("preview.png"); part.setHeader("Content-ID", "preview"); multipart.addBodyPart(part); // // third part in HTML with embedded image // part = new MimeBodyPart(); // part.setContent( "<img src='cid:preview'>", "text/html" ); // multipart.addBodyPart( part ); msg.setContent(multipart); } else { msg.setText(messageText, "utf-8"); } msg.setSentDate(new Date()); Transport.send(msg); }
From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java
public void sendMail(Mail mail) { LOG.debug("sendEmail() to: " + mail.getRecipient()); try {//from ww w . j a va 2s . c om Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator); session.setDebug(false); MimeMessage msg = new MimeMessage(session); msg.setFrom(m_bag.m_fromAddress); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient())); msg.setSubject(mail.getSubject()); msg.setSentDate(new Date()); Multipart mp = new MimeMultipart(); MimeBodyPart txtmbp = new MimeBodyPart(); txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE); mp.addBodyPart(txtmbp); List<String> attachments = mail.getAttachments(); for (Iterator<String> it = attachments.iterator(); it.hasNext();) { MimeBodyPart mbp = new MimeBodyPart(); String filename = it.next(); FileDataSource fds = new FileDataSource(filename); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeText(fds.getName())); mp.addBodyPart(mbp); } msg.setContent(mp); if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null) && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) { cheat(msg, m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@"))); } Transport.send(msg); LOG.info("Successfully send the mail to " + mail.getRecipient()); } catch (Throwable e) { LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e); LOG.debug("Details:", e); } }
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }/*from w w w. j a v a 2s .c om*/ if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:org.xwiki.mail.integration.JavaIntegrationTest.java
@Test public void sendTextMail() throws Exception { // Step 1: Create a JavaMail Session Session session = Session.getInstance(this.configuration.getAllProperties()); // Step 2: Create the Message to send MimeMessage message = new MimeMessage(session); message.setSubject("subject"); message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com")); // Step 3: Add the Message Body Multipart multipart = new MimeMultipart("mixed"); // Add text in the body multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here", Collections.<String, Object>singletonMap("mimetype", "text/plain"))); message.setContent(multipart);/* ww w.j a v a 2 s . com*/ // We also test using some default BCC addresses from configuration in this test this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com")); // Ensure we do not reuse the same message identifier for multiple similar messages in this test MimeMessage message2 = new MimeMessage(message); message2.saveChanges(); MimeMessage message3 = new MimeMessage(message); message3.saveChanges(); // Step 4: Send the mail and wait for it to be sent // Send 3 mails (3 times the same mail) to verify we can send several emails at once. MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory"); this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener); // Note: we don't test status reporting from the listener since this is already tested in the // ScriptingIntegrationTest test class. // Verify that the mails have been received (wait maximum 30 seconds). this.mail.waitForIncomingEmail(30000L, 3); MimeMessage[] messages = this.mail.getReceivedMessages(); // Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)! assertEquals(9, messages.length); // Assert the email parts that are the same for all mails assertEquals("subject", messages[0].getHeader("Subject", null)); assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount()); BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0); assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]); assertEquals("some text here", textBodyPart.getContent()); assertEquals("john@doe.com", messages[0].getHeader("To", null)); // Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received // messages ;) But we checked that we received 9 emails above so that's good enough. }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;//ww w .j a v a2s . c om props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:org.xwiki.mail.integration.JavaIntegrationTest.java
@Test public void sendHTMLAndCalendarInvitationMail() throws Exception { // Step 1: Create a JavaMail Session Session session = Session.getInstance(this.configuration.getAllProperties()); // Step 2: Create the Message to send MimeMessage message = new MimeMessage(session); message.setSubject("subject"); message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com")); // Step 3: Add the Message Body Multipart multipart = new MimeMultipart("alternative"); // Add an HTML body part multipart.addBodyPart( this.htmlBodyPartFactory.create("<font size=\"\\\"2\\\"\">simple meeting invitation</font>", Collections.<String, Object>emptyMap())); // Add the Calendar invitation body part String calendarContent = "BEGIN:VCALENDAR\r\n" + "METHOD:REQUEST\r\n" + "PRODID: Meeting\r\n" + "VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "DTSTAMP:20140616T164100\r\n" + "DTSTART:20140616T164100\r\n" + "DTEND:20140616T194100\r\n" + "SUMMARY:test request\r\n" + "UID:324\r\n" + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:john@doe.com\r\n" + "ORGANIZER:MAILTO:john@doe.com\r\n" + "LOCATION:on the net\r\n" + "DESCRIPTION:learn some stuff\r\n" + "SEQUENCE:0\r\n" + "PRIORITY:5\r\n" + "CLASS:PUBLIC\r\n" + "STATUS:CONFIRMED\r\n" + "TRANSP:OPAQUE\r\n" + "BEGIN:VALARM\r\n" + "ACTION:DISPLAY\r\n" + "DESCRIPTION:REMINDER\r\n" + "TRIGGER;RELATED=START:-PT00H15M00S\r\n" + "END:VALARM\r\n" + "END:VEVENT\r\n" + "END:VCALENDAR"; Map<String, Object> parameters = new HashMap<>(); parameters.put("mimetype", "text/calendar;method=CANCEL"); parameters.put("headers", Collections.singletonMap("Content-Class", "urn:content-classes:calendarmessage")); multipart.addBodyPart(this.defaultBodyPartFactory.create(calendarContent, parameters)); message.setContent(multipart);/*from www .ja v a2 s .c o m*/ // Step 4: Send the mail and wait for it to be sent this.sender.sendAsynchronously(Arrays.asList(message), session, null); // Verify that the mail has been received (wait maximum 30 seconds). this.mail.waitForIncomingEmail(30000L, 1); MimeMessage[] messages = this.mail.getReceivedMessages(); assertEquals("subject", messages[0].getHeader("Subject", null)); assertEquals("john@doe.com", messages[0].getHeader("To", null)); assertEquals(2, ((MimeMultipart) messages[0].getContent()).getCount()); BodyPart htmlBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0); assertEquals("text/html; charset=UTF-8", htmlBodyPart.getHeader("Content-Type")[0]); assertEquals("<font size=\"\\\"2\\\"\">simple meeting invitation</font>", htmlBodyPart.getContent()); BodyPart calendarBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(1); assertEquals("text/calendar;method=CANCEL", calendarBodyPart.getHeader("Content-Type")[0]); InputStream is = (InputStream) calendarBodyPart.getContent(); assertEquals(calendarContent, IOUtils.toString(is)); }