List of usage examples for javax.mail.internet MimeMessage addRecipient
public void addRecipient(RecipientType type, Address address) throws MessagingException
From source file:ee.cyber.licensing.service.MailService.java
public void sendExpirationNearingMail(License license) throws IOException, MessagingException { logger.info("1st ===> setup Mail Server Properties"); Properties mailServerProperties = getProperties(); final String email = mailServerProperties.getProperty("fromEmail"); final String password = mailServerProperties.getProperty("password"); final String host = mailServerProperties.getProperty("mail.smtp.host"); final String mailTo = mailServerProperties.getProperty("mailTo"); logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument"); Authenticator authentication = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(email, password); }/*from w w w . ja v a2 s . c om*/ }; logger.info("Mail Server Properties have been setup successfully"); logger.info("3rd ===> get Mail Session.."); Session getMailSession = Session.getInstance(mailServerProperties, authentication); logger.info("4th ===> generateAndSendEmail() starts"); MimeMessage mailMessage = new MimeMessage(getMailSession); mailMessage.addHeader("Content-type", "text/html; charset=UTF-8"); mailMessage.addHeader("format", "flowed"); mailMessage.addHeader("Content-Transfer-Encoding", "8bit"); mailMessage.setFrom(new InternetAddress(email, "Licensing service")); mailMessage.setSubject("License with id " + license.getId() + " is expiring"); mailMessage.setSentDate(new Date()); mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); String emailBody = "This is test<br><br> Regards, <br>Licensing team"; mailMessage.setContent(emailBody, "text/html"); logger.info("5th ===> Get Session"); sendMail(email, password, host, getMailSession, mailMessage); }
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 .j a va2 s. com 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 w w w. j a v a 2s . 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:org.wso2.carbon.apimgt.core.impl.NewApiVersionMailNotifier.java
@Override public void sendNotifications(NotificationDTO notificationDTO) throws APIManagementException { Properties props = notificationDTO.getProperties(); //get Notifier email List Set<String> emailList = getEmailNotifierList(notificationDTO); if (emailList.isEmpty()) { log.debug("Email Notifier Set is Empty"); return;//from w w w. j a va2 s .co m } for (String mail : emailList) { try { Authenticator auth = new SMTPAuthenticator(); Session mailSession = Session.getDefaultInstance(props, auth); MimeMessage message = new MimeMessage(mailSession); notificationDTO.setTitle((String) notificationDTO.getProperty(NotifierConstants.TITLE_KEY)); notificationDTO.setMessage((String) notificationDTO.getProperty(NotifierConstants.TEMPLATE_KEY)); notificationDTO = loadMailTemplate(notificationDTO); message.setSubject(notificationDTO.getTitle()); message.setContent(notificationDTO.getMessage(), NotifierConstants.TEXT_TYPE); message.setFrom(new InternetAddress(mailConfigurations.getFromUser())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail)); Transport.send(message); } catch (MessagingException e) { log.error("Exception Occurred during Email notification Sending", e); } } }
From source file:org.xwiki.watchlist.internal.notification.WatchListEventMimeMessageIterator.java
@Override public MimeMessage next() { MimeMessage message; WatchListMessageData watchListMessageData = this.subscriberIterator.next(); try {/* w w w.j a v a 2 s . c om*/ // Update the values for this new message. updateFactoryParameters(factoryParameters, watchListMessageData); DocumentReference factorySource = watchListMessageData.getTemplateReference(); // Use the factory to create the message. message = this.factory.createMessage(factorySource, factoryParameters); message.addRecipient(Message.RecipientType.TO, watchListMessageData.getAddress()); // Set conversation headers. message = setConversationHeaders(message, watchListMessageData); } catch (MessagingException e) { throw new RuntimeException("Failed to create Mime Message, aborting mail sending for this batch", e); } return message; }
From source file:org.beangle.notification.notifiers.mail.AbstractMailNotifier.java
private int addRecipient(MimeMessage mimeMsg, MailMessage mailMsg) throws MessagingException { String encoding = mailMsg.getEncoding(); if (null == froms) { List<InternetAddress> addresses = MimeUtils.parseAddress(from, encoding); InternetAddress[] addressArray = new InternetAddress[addresses.size()]; if (addressArray.length > 0) { addresses.toArray(addressArray); froms = addressArray;/*from ww w .ja v a2 s. c o m*/ } } int recipients = 0; if (null != froms) mimeMsg.addFrom(froms); for (InternetAddress to : mailMsg.getTo()) { mimeMsg.addRecipient(javax.mail.Message.RecipientType.TO, to); recipients++; } for (InternetAddress cc : mailMsg.getCc()) { mimeMsg.addRecipient(javax.mail.Message.RecipientType.CC, cc); recipients++; } for (InternetAddress bcc : mailMsg.getBcc()) { mimeMsg.addRecipient(javax.mail.Message.RecipientType.BCC, bcc); recipients++; } return recipients; }
From source file:org.tsm.concharto.web.feedback.FeedbackController.java
public MimeMessage makeFeedbackMessage(MimeMessage message, FeedbackForm feedbackForm, HttpServletRequest request) {//w ww. ja va 2 s . c o m //prepare the user info String requestInfo = getBrowserInfo(request); StringBuffer messageText = new StringBuffer(feedbackForm.getBody()) .append("\n\n=============================================================\n").append(requestInfo); InternetAddress from = new InternetAddress(); from.setAddress(feedbackForm.getEmail()); InternetAddress to = new InternetAddress(); to.setAddress(sendFeedbackToAddress); try { from.setPersonal(feedbackForm.getName()); message.addRecipient(Message.RecipientType.TO, to); message.setSubject(FEEDBACK_SUBJECT + feedbackForm.getSubject()); message.setText(messageText.toString()); message.setFrom(from); } catch (UnsupportedEncodingException e) { log.error(e); } catch (MessagingException e) { log.error(e); } return message; }
From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java
@Override public void sendNotification(String smtpSender, String replyTo, String recipient, String subject, String htmlContent, String inReplyTo, String references) throws SendFailedException { if (smtpServer.equals("")) { logger.warn("Mail notifications are disabled."); return;//from w ww . j a v a 2s .co m } // get the mail session Session session = getMailSession(); // Define message MimeMessage messageMim = new MimeMessage(session); try { messageMim.setFrom(new InternetAddress(smtpSender)); if (replyTo != null) { InternetAddress reply[] = new InternetAddress[1]; reply[0] = new InternetAddress(replyTo); messageMim.setReplyTo(reply); } messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); if (inReplyTo != null && inReplyTo != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(inReplyTo)) { messageMim.setHeader("In-Reply-To", inReplyTo); } } if (references != null && references != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(references)) { messageMim.setHeader("References", references); } } messageMim.setSubject(subject, charset); // Create a "related" Multipart message // content type is multipart/alternative // it will contain two part BodyPart 1 and 2 Multipart mp = new MimeMultipart("alternative"); // BodyPart 2 // content type is multipart/related // A multipart/related is used to indicate that message parts should // not be considered individually but rather // as parts of an aggregate whole. The message consists of a root // part (by default, the first) which reference other parts inline, // which may in turn reference other parts. Multipart html_mp = new MimeMultipart("related"); // Include an HTML message with images. // BodyParts: the HTML file and an image // Get the HTML file BodyPart rel_bph = new MimeBodyPart(); rel_bph.setDataHandler( new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset))); html_mp.addBodyPart(rel_bph); // Create the second BodyPart of the multipart/alternative, // set its content to the html multipart, and add the // second bodypart to the main multipart. BodyPart alt_bp2 = new MimeBodyPart(); alt_bp2.setContent(html_mp); mp.addBodyPart(alt_bp2); messageMim.setContent(mp); // RFC 822 "Date" header field // Indicates that the message is complete and ready for delivery messageMim.setSentDate(new GregorianCalendar().getTime()); // Since we used html tags, the content must be marker as text/html // messageMim.setContent(content,"text/html; charset="+charset); Transport tr = session.getTransport("smtp"); // Connect to smtp server, if needed if (needsAuth) { tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword); messageMim.saveChanges(); tr.sendMessage(messageMim, messageMim.getAllRecipients()); tr.close(); } else { // Send message Transport.send(messageMim); } } catch (SendFailedException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient, e); throw e; } catch (MessagingException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } catch (Exception e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } }
From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server/*ww w . j a v a 2s . c o m*/ * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Properties props = System.getProperties(); props.put("mail.smtp.host", this.emailFactory.getSmtpHost()); props.put("mail.protocol.port", this.emailFactory.getSmtpPort()); final Session session = Session.getInstance(props, null); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server//w ww . jav a 2 s .c o m * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }