List of usage examples for javax.mail.internet MimeMessage setContent
@Override public void setContent(Multipart mp) throws MessagingException
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private MimeMessage prepareHTMLMimeMessage(InternetAddress internetAddressFrom, String subject, String htmlBody, List<LabelValueBean> attachments) throws Exception { MimeMessage msg = new MimeMessage(session); msg.setFrom(internetAddressFrom);/* w w w.java 2 s .c o m*/ msg.setHeader(XMAILER, xmailer); msg.setSubject(subject.trim(), mailEncoding); msg.setSentDate(new Date()); MimeMultipart mimeMultipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); //Euro sign finally, shown correctly messageBodyPart.setContent(htmlBody, "text/html;charset=" + mailEncoding); mimeMultipart.addBodyPart(messageBodyPart); if (attachments != null && !attachments.isEmpty()) { LOGGER.debug("Use attachments: " + attachments.size()); includeAttachments(mimeMultipart, attachments); } msg.setContent(mimeMultipart); return msg; }
From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java
/** * Perform the primary function of this component, this is, to execute. This method will be invoked immediately following a successful validate(). * <p/>//from ww w .ja v a 2 s. c o m * This method has 2 ways of working: * <p/> * 1. You supply a mimeMessage: That mimeMessage will be sent; * Optionally, contents will be added as attachment and the original * mimeMessage will be encapsulated under a multipart/mixed * <p/> * <p/> * 2. You supply a messageHtml and/or a messageText. A new mimemessage will be * built. If you supply both, a multipart/alternative will be used. After that * attachments will be included * * @return true if successful execution * @throws Exception */ public boolean execute() throws Exception { try { // Get the session object final Session session = buildSession(); // Create the message final MimeMessage msg = new MimeMessage(session); // From, to, etc. applyMessageHeaders(msg); // Get main message multipart final Multipart multipartBody = getMultipartBody(session); // Process attachments final Multipart mainMultiPart = processAttachments(multipartBody); msg.setContent(mainMultiPart); // Send it msg.setHeader("X-Mailer", MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { log.error(Messages.getInstance().getString("ReportPlugin.emailSendFailed")); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { log.error(Messages.getInstance().getString("ReportPlugin.emailAuthenticationFailed")); //$NON-NLS-1$ } return false; }
From source file:app.logica.gestores.GestorEmail.java
/** * Create a MimeMessage using the parameters provided. * * @param to//from w w w . j av a 2s.co m * 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. * @param file * Path to the file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, File file) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); email.setFrom(new InternetAddress(from)); email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(file); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(file.getName()); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:com.cosmicpush.plugins.smtp.EmailMessage.java
/** * @param session the applications current session. * @throws EmailMessageException in response to any other type of exception. *//* w w w . j av a 2 s. c om*/ @SuppressWarnings({ "ConstantConditions" }) protected void send(Session session) throws EmailMessageException { try { // create a message MimeMessage msg = new MimeMessage(session); //set some of the basic attributes. msg.setFrom(fromAddress); msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses)); msg.setSubject(subject); msg.setSentDate(new Date()); if (replyToAddress.isEmpty() == false) { msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress)); } // create the Multipart and add set it as the content of the message Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // create and fill the HTML part of the messgae if it exists if (html != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(html, "UTF-8", "html"); multipart.addBodyPart(bodyPart); } // create and fill the text part of the messgae if it exists if (text != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(text, "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } if (html == null && text == null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText("", "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } // remove any nulls from the list of attachments. while (attachments.remove(null)) { /* keep going */ } // Attach any files that we have, making sure that they exist first for (File file : attachments) { if (file.exists() == false) { throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist."); } else { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(file); multipart.addBodyPart(attachmentPart); } } // send the message Transport.send(msg); } catch (EmailMessageException ex) { throw ex; } catch (Exception ex) { throw new EmailMessageException("Exception sending email\n" + toString(), ex); } }
From source file:org.tizzit.util.mail.MailHelper.java
/** * Send an email in html-format in iso-8859-1-encoding * // ww w. ja v a 2 s .co m * @param subject the subject of the new mail * @param htmlMessage the content of the mail as html * @param alternativeTextMessage the content of the mail as text * @param from the sender-address * @param to the receiver-address * @param cc the address of the receiver of a copy of this mail * @param bcc the address of the receiver of a blind-copy of this mail */ public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from, String[] to, String[] cc, String[] bcc) { try { MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); if (cc != null && cc.length != 0) { for (int i = cc.length - 1; i >= 0; i--) { msg.addRecipients(Message.RecipientType.CC, cc[i]); } } if (bcc != null && bcc.length != 0) { for (int i = bcc.length - 1; i >= 0; i--) { msg.addRecipients(Message.RecipientType.BCC, bcc[i]); } } if (to != null && to.length != 0) { for (int i = to.length - 1; i >= 0; i--) { msg.addRecipients(Message.RecipientType.TO, to[i]); } } msg.setSubject(subject, "ISO8859_1"); msg.setSentDate(new Date()); MimeMultipart multiPart = new MimeMultipart("alternative"); MimeBodyPart htmlPart = new MimeBodyPart(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(alternativeTextMessage, "ISO8859_1"); textPart.setHeader("MIME-Version", "1.0"); //textPart.setHeader("Content-Type", textPart.getContentType()); textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\""); htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\""); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\""); //htmlPart.setHeader("Content-Type", htmlPart.getContentType()); multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); multiPart.setSubType("alternative"); msg.setContent(multiPart); msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", multiPart.getContentType()); Transport.send(msg); } catch (Exception e) { log.error("Error sending html-mail: " + e.getLocalizedMessage()); } }
From source file:be.fedict.eid.dss.model.bean.TaskMDB.java
private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype, byte[] attachment) { LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\""); String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class); if (null == smtpServer || smtpServer.trim().isEmpty()) { LOG.warn("no SMTP server configured"); return;/* ww w.ja v a 2 s . c o m*/ } String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class); if (null == mailFrom || mailFrom.trim().isEmpty()) { LOG.warn("no mail from address configured"); return; } LOG.debug("mail from: " + mailFrom); Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); props.put("mail.from", mailFrom); String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class); if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) { subject = "[" + mailPrefix.trim() + "] " + subject; } Session session = Session.getInstance(props, null); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(); mimeMessage.setRecipients(RecipientType.TO, mailTo); mimeMessage.setSubject(subject); mimeMessage.setSentDate(new Date()); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(messageBody); Multipart multipart = new MimeMultipart(); // first part is body multipart.addBodyPart(mimeBodyPart); // second part is attachment if (null != attachment) { MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart(); DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype); attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource)); multipart.addBodyPart(attachmentMimeBodyPart); } mimeMessage.setContent(multipart); Transport.send(mimeMessage); } catch (MessagingException e) { throw new RuntimeException("send failed, exception: " + e.getMessage(), e); } }
From source file:com.jwm123.loggly.reporter.ReportMailer.java
public void send() throws MessagingException { if (StringUtils.isNotBlank(config.getMailServer()) && recipients.length > 0) { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.port", config.getMailPort().toString()); props.setProperty("mail.smtp.host", config.getMailServer()); if (StringUtils.isNotBlank(config.getMailUsername()) && StringUtils.isNotBlank(config.getMailPassword())) { props.setProperty("mail.smtp.user", config.getMailUsername()); props.setProperty("mail.smtp.password", config.getMailPassword()); }/* ww w. ja va2s .co m*/ Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.addFrom(new Address[] { new InternetAddress(config.getMailFrom()) }); message.setSubject(subject); for (String recipient : recipients) { message.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } MimeMultipart containingMultipart = new MimeMultipart("mixed"); MimeMultipart messageMultipart = new MimeMultipart("alternative"); containingMultipart.addBodyPart(newMultipartBodyPart(messageMultipart)); messageMultipart.addBodyPart(newTextBodyPart(getText())); MimeMultipart htmlMultipart = new MimeMultipart("related"); htmlMultipart.addBodyPart(newHtmlBodyPart(getHtml())); messageMultipart.addBodyPart(newMultipartBodyPart(htmlMultipart)); containingMultipart.addBodyPart(addReportAttachment()); message.setContent(containingMultipart); Transport.send(message); } }
From source file:com.haulmont.cuba.core.app.EmailSender.java
protected MimeMessage createMimeMessage(SendingMessage sendingMessage) throws MessagingException { MimeMessage msg = mailSender.createMimeMessage(); assignRecipient(sendingMessage, msg); msg.setSubject(sendingMessage.getCaption(), StandardCharsets.UTF_8.name()); msg.setSentDate(timeSource.currentTimestamp()); assignFromAddress(sendingMessage, msg); addHeaders(sendingMessage, msg);// w w w. j a va2 s . c o m MimeMultipart content = new MimeMultipart("mixed"); MimeMultipart textPart = new MimeMultipart("related"); setMimeMessageContent(sendingMessage, content, textPart); for (SendingAttachment attachment : sendingMessage.getAttachments()) { MimeBodyPart attachmentPart = createAttachmentPart(attachment); if (attachment.getContentId() == null) { content.addBodyPart(attachmentPart); } else textPart.addBodyPart(attachmentPart); } msg.setContent(content); msg.saveChanges(); return msg; }
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 av a 2 s. co 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:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java
protected void send(String subject, String content, String contentType) throws Exception { Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", getHost()); props.put("mail.smtps.auth", "true"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(false);/*from ww w.j ava2s . c om*/ Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr")); message.setSubject(subject); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "utf-8"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); List<String> fileNames = getAtchFileIds(); for (Iterator<String> it = fileNames.iterator(); it.hasNext();) { MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(it.next()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : mp.addBodyPart(mbp2); } // add the Multipart to the message message.setContent(mp); for (Iterator<String> it = getReceivers().iterator(); it.hasNext();) message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next())); transport.connect(getHost(), getPort(), getUsername(), getPassword()); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); }