List of usage examples for javax.mail Multipart addBodyPart
public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java
/** * Attaches a file as a body part to the multipart message * * @param multipart/* w ww . ja v a 2 s . co m*/ * @param attachment * @throws MessagingException */ private void addPart(Multipart multipart, Message msg) throws MessagingException { MimeBodyPart part = new MimeBodyPart(); part.setContent(msg.getBody(), msg.getType()); multipart.addBodyPart(part); }
From source file:pt.ist.fenix.api.SupportFormResource.java
private void sendEmail(String from, String subject, String body, SupportBean bean) { Properties props = new Properties(); props.put("mail.smtp.host", Objects .firstNonNull(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), "localhost")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); try {/* w w w.j a v a 2 s .c o m*/ message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress())); message.setSubject(subject); message.setText(body); Multipart multipart = new MimeMultipart(); { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); } if (!Strings.isNullOrEmpty(bean.attachment)) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(Base64.getDecoder().decode(bean.attachment), bean.mimeType))); messageBodyPart.setFileName(bean.fileName); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); Transport.send(message); } catch (Exception e) { logger.error("Could not send support email! Original message was: " + body, e); } }
From source file:com.threewks.thundr.gmail.GmailMailer.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email. * @param bodyText Body text of the email. * @return MimeMessage to be used to send email. * @throws MessagingException// www . jav a 2 s. c o m */ protected MimeMessage createEmailWithAttachment(Set<InternetAddress> to, InternetAddress from, Set<InternetAddress> cc, Set<InternetAddress> bcc, InternetAddress replyTo, String subject, String bodyText, List<com.threewks.thundr.mail.Attachment> attachments) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); try { email.setFrom(from); if (to != null) { email.addRecipients(javax.mail.Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()])); } if (cc != null) { email.addRecipients(javax.mail.Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()])); } if (bcc != null) { email.addRecipients(javax.mail.Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()])); } if (replyTo != null) { email.setReplyTo(new Address[] { replyTo }); } email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/html"); mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); if (attachments != null) { for (com.threewks.thundr.mail.Attachment attachment : attachments) { mimeBodyPart = new MimeBodyPart(); BasicViewRenderer renderer = new BasicViewRenderer(viewResolverRegistry); renderer.render(attachment.view()); byte[] data = renderer.getOutputAsBytes(); String attachmentContentType = renderer.getContentType(); String attachmentCharacterEncoding = renderer.getCharacterEncoding(); populateMimeBodyPart(mimeBodyPart, attachment, data, attachmentContentType, attachmentCharacterEncoding); multipart.addBodyPart(mimeBodyPart); } } email.setContent(multipart); } catch (MessagingException e) { Logger.error(e.getMessage()); Logger.error( "Failed to create email from: %s;%s, to: %s, cc: %s, bcc: %s, replyTo %s;%s, subject %s, body %s, number of attachments %d", from.getAddress(), from.getPersonal(), Transformers.InternetAddressesToString.from(to), Transformers.InternetAddressesToString.from(cc), Transformers.InternetAddressesToString.from(bcc), replyTo == null ? "null" : replyTo.getAddress(), replyTo == null ? "null" : replyTo.getPersonal(), subject, bodyText, attachments == null ? 0 : attachments.size()); throw new GmailException(e); } return email; }
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 {/* w w w . j a v a 2 s .c om*/ // 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:org.artifactory.mail.MailServiceImpl.java
/** * Send an e-mail message//from w w w . j a v a 2 s . c o m * * @param recipients Recipients of the message that will be sent * @param subject The subject of the message * @param body The body of the message * @param config A mail server configuration to use * @throws Exception */ @Override public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config) throws EmailException { verifyParameters(recipients, config); if (!config.isEnabled()) { log.debug("Ignoring requested mail delivery. The given configuration is disabled."); return; } boolean debugEnabled = log.isDebugEnabled(); Properties properties = new Properties(); properties.put("mail.smtp.host", config.getHost()); properties.put("mail.smtp.port", Integer.toString(config.getPort())); properties.put("mail.smtp.quitwait", "false"); //Default protocol String protocol = "smtp"; //Enable TLS if set if (config.isUseTls()) { properties.put("mail.smtp.starttls.enable", "true"); } //Enable SSL if set boolean useSsl = config.isUseSsl(); if (useSsl) { properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort())); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); //Requires special protocol protocol = "smtps"; } //Set debug property if enabled by the logger properties.put("mail.debug", debugEnabled); Authenticator authenticator = null; if (!StringUtils.isEmpty(config.getUsername())) { properties.put("mail.smtp.auth", "true"); authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getUsername(), config.getPassword()); } }; } Session session = Session.getInstance(properties, authenticator); Message message = new MimeMessage(session); String subjectPrefix = config.getSubjectPrefix(); String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject; try { message.setSubject(fullSubject); if (!StringUtils.isEmpty(config.getFrom())) { InternetAddress addressFrom = new InternetAddress(config.getFrom()); message.setFrom(addressFrom); } InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } message.addRecipients(Message.RecipientType.TO, addressTo); //Create multi-part message in case we want to add html support Multipart multipart = new MimeMultipart("related"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(body, "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); //Set debug property if enabled by the logger session.setDebug(debugEnabled); //Connect and send Transport transport = session.getTransport(protocol); if (useSsl) { transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException e) { String em = e.getMessage(); throw new EmailException( "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n", e); } }
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 w w w .ja va 2 s . c o m 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:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailTextWithAttachment() 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("Plain text Email test with attachment"); MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.INLINE); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setText(textEmailContent);//from ww w . j a va2 s .c om Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); mail.setSentDate(new Date()); Date sentDate = new Date(mail.getSentDate().getTime()); 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("Plain text Email test with attachment", message.getTitle()); assertEquals(textEmailContent, message.getBody()); assertEquals(textEmailContent.substring(0, 200), 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(sentDate.getTime(), message.getSentDate().getTime()); assertEquals("text/plain", message.getContentType()); org.jvnet.mock_javamail.Mailbox.clearAll(); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); verify(mockListener1, times(2)).getComponentId(); }
From source file:com.waveerp.sendMail.java
public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg, String strDestination, String strDestDesc, String strPath) throws Exception { String strResult = "OK"; // Call the registry management system registrySystem rs = new registrySystem(); // Call the encryption management system desEncryption de = new desEncryption(); de.Encrypter("", ""); String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST"); String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT"); final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER"); String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD"); //Decrypt the encrypted password. final String strPass01 = de.decrypt(strPass); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", strHost); props.put("mail.smtp.port", strPort); props.put("mail.user", strUser); props.put("mail.password", strPass01); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPass01); }/* ww w . j av a2 s . com*/ }; Session session = Session.getInstance(props, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(strSource)); //InternetAddress[] toAddresses = { new InternetAddress(strDestination) }; msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination)); msg.setSubject(strSubject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(strMsg, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments //if (attachFiles != null && attachFiles.length > 0) { // for (String filePath : attachFiles) { // MimeBodyPart attachPart = new MimeBodyPart(); // // try { // attachPart.attachFile(filePath); // } catch (IOException ex) { // ex.printStackTrace(); // } // // multipart.addBodyPart(attachPart); // } //} String fna; String fnb; URL fileUrl; fileUrl = null; fileUrl = this.getClass().getResource("sendMail.class"); fna = fileUrl.getPath(); fna = fna.substring(0, fna.indexOf("WEB-INF")); //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath ); fnb = URLDecoder.decode(fna + strPath); MimeBodyPart attachPart = new MimeBodyPart(); try { attachPart.attachFile(fnb); } catch (IOException ex) { //ex.printStackTrace(); strResult = ex.getMessage(); } multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); return strResult; }
From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java
private void addBody(MimeMessage msg) throws MessagingException { if (body != null) { Multipart multipart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(body, contentType()); multipart.addBodyPart(bodyPart); msg.setContent(multipart);/*from w ww.j ava 2 s . c om*/ } }
From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java
@Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void onMessage(Message arg0) { ObjectMessage objectMessage = (ObjectMessage) arg0; try {/*from ww w . j a v a 2s.co m*/ Mail mail = (Mail) objectMessage.getObject(); // Get properties String mailProtocol = getMailProtocol(); String mailServer = getSmtpServer(); String mailUser = getSmtpUser(); String mailPort = getSmtpPort(); String mailPassword = getSmtpPassword(); // Initialize a mail session Properties props = new Properties(); props.put("mail." + mailProtocol + ".host", mailServer); props.put("mail." + mailProtocol + ".port", mailPort); Session session = Session.getInstance(props); // Create the message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(mail.getSender())); for (String recipient : mail.getRecipients()) { msg.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } msg.setSubject(mail.getSubject(), "UTF-8"); Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // Set the email message text and attachment MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setContent(mail.getBody(), mail.getContentType()); multipart.addBodyPart(messagePart); if (mail.getAttachmentData() != null) { ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(), mail.getAttachmentContentType()); DataHandler dataHandler = new DataHandler(byteArrayDataSource); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(dataHandler); attachmentPart.setFileName(mail.getAttachmentFileName()); multipart.addBodyPart(attachmentPart); } // Open transport and send message Transport transport = session.getTransport(mailProtocol); if (StringUtils.isNotBlank(mailUser)) { transport.connect(mailUser, mailPassword); } else { transport.connect(); } msg.saveChanges(); transport.sendMessage(msg, msg.getAllRecipients()); } catch (JMSException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e); throw new RuntimeException(e); } catch (MessagingException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e); throw new RuntimeException(e); } }