List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. From source file:com.silverpeas.mailinglist.service.job.TestMessageCheckerWithStubs.java
@Test public void testCheckNewMessages() throws MessagingException, IOException { org.jvnet.mock_javamail.Mailbox.clearAll(); MessageChecker messageChecker = getMessageChecker(); messageChecker.removeListener("componentId"); messageChecker.removeListener("thesimpsons@silverpeas.com"); messageChecker.removeListener("theflanders@silverpeas.com"); StubMessageListener mockListener1 = new StubMessageListener("thesimpsons@silverpeas.com"); StubMessageListener mockListener2 = new StubMessageListener("theflanders@silverpeas.com"); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(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( TestMessageCheckerWithStubs.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 2 s .c o m*/ Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); mail.setSentDate(new Date()); Date sentDate1 = new Date(mail.getSentDate().getTime()); Transport.send(mail); mail = new MimeMessage(messageChecker.getMailSession()); bart = new InternetAddress("bart.simpson@silverpeas.com"); theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test"); mail.setText(textEmailContent); mail.setSentDate(new Date()); Date sentDate2 = new Date(mail.getSentDate().getTime()); Transport.send(mail); //Unauthorized email mail = new MimeMessage(messageChecker.getMailSession()); bart = new InternetAddress("marge.simpson@silverpeas.com"); theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test"); mail.setText(textEmailContent); mail.setSentDate(new Date()); Transport.send(mail); assertThat(org.jvnet.mock_javamail.Mailbox.get("thesimpsons@silverpeas.com").size(), is(3)); messageChecker.checkNewMessages(new Date()); assertThat(mockListener2.getMessageEvent(), is(nullValue())); MessageEvent event = mockListener1.getMessageEvent(); assertThat(event, is(notNullValue())); assertThat(event.getMessages(), is(notNullValue())); assertThat(event.getMessages(), hasSize(2)); Message message = event.getMessages().get(0); assertThat(message.getSender(), is("bart.simpson@silverpeas.com")); assertThat(message.getTitle(), is("Plain text Email test with attachment")); assertThat(message.getBody(), is(textEmailContent)); assertThat(message.getSummary(), is(textEmailContent.substring(0, 200))); assertThat(message.getSentDate().getTime(), is(sentDate1.getTime())); assertThat(message.getAttachmentsSize(), greaterThan(0L)); assertThat(message.getAttachments(), hasSize(1)); String path = MessageFormat.format(theSimpsonsAttachmentPath, new Object[] { messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()) }); Attachment attached = message.getAttachments().iterator().next(); assertThat(attached.getPath(), is(path)); assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com")); message = event.getMessages().get(1); assertThat(message.getSender(), is("bart.simpson@silverpeas.com")); assertThat(message.getTitle(), is("Plain text Email test")); assertThat(message.getBody(), is(textEmailContent)); assertThat(message.getSummary(), is(textEmailContent.substring(0, 200))); assertThat(message.getAttachmentsSize(), is(0L)); assertThat(message.getAttachments(), hasSize(0)); assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com")); assertThat(message.getSentDate().getTime(), is(sentDate2.getTime())); }
From source file:com.mylab.mail.OpenCmsMailService.java
public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException { log.debug("Sending multipart message " + config); Session session = getSession();/*from w ww . j av a 2s . c o m*/ MimeMultipart multipart = new MimeMultipart(); MimeBodyPart html = new MimeBodyPart(); html.setContent(config.getContent(), config.getContentType()); html.setHeader("MIME-Version", "1.0"); html.setHeader("Content-Type", html.getContentType()); multipart.addBodyPart(html); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(ds)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); final MimeMessage message = new MimeMessage(session); message.setContent(multipart); try { message.setFrom(new InternetAddress(config.getFrom(), config.getFromName())); addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig()); } catch (UnsupportedEncodingException ex) { throw new MessagingException("Setting from or to failed", ex); } message.setSubject(config.getSubject()); // we don't send in a new Thread so that we get the Exception Transport.send(message); }
From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java
public boolean send() { try {//w w w. j a v a2s . com MimeMessage msg = new MimeMessage(mailSession); msg.setReplyTo(new Address[] { replyToAddress }); if (fromAddress == null) { msg.addFrom(new Address[] { replyToAddress }); } else { msg.addFrom(new Address[] { fromAddress }); } for (Recipient recipient : recipients) { msg.addRecipient(recipient.type, recipient.address); } msg.setSubject(subject); if (textContent.isEmpty()) { if (htmlContent.isEmpty()) { log.error("Message has neither text body nor HTML body"); } else { msg.setContent(htmlContent, "text/html"); } } else { if (htmlContent.isEmpty()) { msg.setContent(textContent, "text/plain"); } else { MimeMultipart content = new MimeMultipart("alternative"); addBodyPart(content, textContent, "text/plain"); addBodyPart(content, htmlContent, "text/html"); msg.setContent(content); } } msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (MessagingException e) { log.error("Failed to send message.", e); return false; } }
From source file:com.predic8.membrane.core.interceptor.authentication.session.EmailTokenProvider.java
private void sendEmail(String sender, String recipient, String subject, String text) { try {/*w w w . j a v a 2s . com*/ Properties props = System.getProperties(); props.put("mail.smtp.port", "" + smtpPort); props.put("mail.smtp.socketFactory.port", "" + smtpPort); if (ssl) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.starttls.required", "true"); } if (smtpUser != null) { props.put("mail.smtp.auth", "true"); } Session session = Session.getInstance(props, null); final MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(sender)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false)); msg.setSubject(subject); msg.setText(text, Constants.UTF_8); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp"); t.connect(smtpHost, smtpUser, smtpPassword); t.sendMessage(msg, msg.getAllRecipients()); t.close(); } catch (MessagingException e) { throw new RuntimeException(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"); }/* w ww . ja v a 2 s.co m*/ 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:com.aurel.track.util.emailHandling.MailBuilder.java
/** * Prepares a plain MimeMessage: the MimeMessage.RecipientType.TO is not yet set * @return// www. j a va2 s . co m * @throws Exception */ private MimeMessage preparePlainMimeMessage(InternetAddress internetAddressFrom, String subject, String plainBody, List<LabelValueBean> attachments) throws Exception { MimeMessage msg = new MimeMessage(session); msg.setFrom(internetAddressFrom); msg.setHeader(XMAILER, xmailer); msg.setSubject(subject.trim(), mailEncoding); msg.setSentDate(new Date()); if (attachments == null || attachments.isEmpty()) { msg.setText(plainBody, mailEncoding); } else { MimeMultipart mimeMultipart = new MimeMultipart(); MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText(plainBody, mailEncoding); mimeMultipart.addBodyPart(textBodyPart); if (attachments != null) { includeAttachments(mimeMultipart, attachments); } msg.setContent(mimeMultipart); } return msg; }
From source file:com.cubusmail.mail.MessageHandler.java
/** * @param session */ private void init(Session session) { init(session, new MimeMessage(session)); }
From source file:eu.scape_project.pw.idp.UserManager.java
/** * Method responsible for sending a email to the user, including a link to * activate his user account./*from w ww .j av a 2 s . c o m*/ * * @param user * User the activation mail should be sent to * @param serverString * Name and port of the server the user was added. * @throws CannotSendMailException * if the mail could not be sent */ public void sendActivationMail(IdpUser user, String serverString) throws CannotSendMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail())); message.setSubject("Please confirm your Planningsuite user account"); StringBuilder builder = new StringBuilder(); builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n"); builder.append("Please use the following link to confirm your Planningsuite user account: \n"); builder.append("http://" + serverString + "/idp/activateUser.jsf?uid=" + user.getActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Activation mail sent successfully to {}", user.getEmail()); } catch (Exception e) { log.error("Error at sending activation mail to {}", user.getEmail()); throw new CannotSendMailException("Error at sending activation mail to " + user.getEmail(), e); } }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testGetAllRecipients() throws AddressException, MessagingException { MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); mail.addFrom(new InternetAddress[] { new InternetAddress("bart.simpson@silverpeas.com") }); mail.addRecipient(RecipientType.TO, new InternetAddress("lisa.simpson@silverpeas.com")); mail.addRecipient(RecipientType.TO, new InternetAddress("marge.simpson@silverpeas.com")); mail.addRecipient(RecipientType.CC, new InternetAddress("homer.simpson@silverpeas.com")); mail.addRecipient(RecipientType.CC, new InternetAddress("krusty.theklown@silverpeas.com")); mail.addRecipient(RecipientType.BCC, new InternetAddress("ned.flanders@silverpeas.com")); mail.addRecipient(RecipientType.BCC, new InternetAddress("ted.flanders@silverpeas.com")); Set<String> recipients = messageChecker.getAllRecipients(mail); assertNotNull(recipients);//from ww w .ja v a 2s. c o m assertEquals(6, recipients.size()); assertTrue(recipients.contains("lisa.simpson@silverpeas.com")); assertTrue(recipients.contains("marge.simpson@silverpeas.com")); assertTrue(recipients.contains("homer.simpson@silverpeas.com")); assertTrue(recipients.contains("krusty.theklown@silverpeas.com")); assertTrue(recipients.contains("ned.flanders@silverpeas.com")); assertTrue(recipients.contains("ted.flanders@silverpeas.com")); }