List of usage examples for org.springframework.mail.javamail MimeMessageHelper setSentDate
public void setSentDate(Date sentDate) throws MessagingException
From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java
/** * {@inheritDoc}/* www. j a v a 2 s. c o m*/ * @see com.mobileman.projecth.business.MailManager#sendTellAFriendMessage(java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override public void sendTellAFriendMessage(final String senderName, final String senderEmail, final String receiverEmails, final String body) { if (log.isDebugEnabled()) { log.debug("sendMessage(" + senderName + ", " + senderEmail + ", " + receiverEmails + ", " + body + ") - start"); } if (senderEmail == null || senderEmail.trim().length() == 0) { throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING); } if (receiverEmails == null || receiverEmails.trim().length() == 0) { throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING); } final String[] senderData = { "", "", "" }; final String[] receivers = receiverEmails.split("[,]"); for (int i = 0; i < receivers.length; i++) { final int idx = i; MimeMessagePreparator preparator = new MimeMessagePreparator() { /** * {@inheritDoc} * @see org.springframework.mail.javamail.MimeMessagePreparator#prepare(javax.mail.internet.MimeMessage) */ @Override public void prepare(MimeMessage mimeMessage) throws Exception { if (log.isDebugEnabled()) { log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$ } MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING); messageHelper.setSentDate(new Date()); Map<String, Object> model = new HashMap<String, Object>(); model.put("body-text", body); String htmlMessage = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "tell-a-friend-email-body.vm", model); String textMessage = HTMLTextParser.htmlToText(htmlMessage); messageHelper.setText(textMessage, htmlMessage); senderData[0] = htmlMessage; senderData[1] = textMessage; senderData[2] = "Mitteilung von projecth"; messageHelper.setSubject(senderData[2]); messageHelper.setTo(receivers[idx]); messageHelper.setFrom(getSystemAdminEmail()); if (log.isDebugEnabled()) { log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$ } } }; this.mailSender.send(preparator); } this.mailSender.send(new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING); messageHelper.setSentDate(new Date()); messageHelper.setText(senderData[1], senderData[0]); messageHelper.setSubject(senderData[2]); messageHelper.setTo(senderEmail); messageHelper.setFrom(getSystemAdminEmail()); } }); if (log.isDebugEnabled()) { log.debug("sendMessage(...) - end"); } }
From source file:org.jnap.core.email.Email.java
public void prepare(MimeMessage mimeMessage) throws Exception { final EmailAccountInfo acc = getAccountInfo(); boolean multipart = StringUtils.isNotBlank(getHtmlText()) || (getInlineResources() != null && getInlineResources().size() > 0) || (getAttachments() != null && getAttachments().size() > 0); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart); if (acc.getFromName() != null) { helper.setFrom(acc.getFromEmailAddress(), acc.getFromName()); } else {//from www . jav a2 s . co m this.setFrom(acc.getFromEmailAddress()); } helper.setTo(getTo()); if (getCc() != null) { helper.setCc(getCc()); } if (getBcc() != null) { helper.setBcc(getBcc()); } helper.setSentDate(new Date()); mimeMessage.setSubject(getMessage(getSubject()), this.encoding); // sender info if (acc != null && StringUtils.isNotBlank(acc.getFromName())) { helper.setFrom(acc.getFromEmailAddress(), getMessage(acc.getFromName())); } else { helper.setFrom(acc.getFromEmailAddress()); } if (acc != null && StringUtils.isNotBlank(acc.getReplyToEmailAddress())) { if (StringUtils.isNotBlank(acc.getReplyToName())) { helper.setReplyTo(acc.getReplyToEmailAddress(), acc.getReplyToName()); } else { helper.setReplyTo(acc.getReplyToEmailAddress()); } } final boolean hasHtmlText = StringUtils.isNotBlank(getHtmlText()); final boolean hasText = StringUtils.isNotBlank(getText()); if (hasHtmlText && hasText) { helper.setText(getText(), getHtmlText()); } else if (hasHtmlText || hasText) { helper.setText(hasHtmlText ? getHtmlText() : getText()); } // set headers final Map<String, String> mailHeaders = this.getHeaders(); for (String header : mailHeaders.keySet()) { mimeMessage.addHeader(header, mailHeaders.get(header)); } // add inline resources final Map<String, Resource> inlineRes = this.getInlineResources(); if (inlineRes != null) { for (String cid : inlineRes.keySet()) { helper.addInline(cid, inlineRes.get(cid)); } } // add attachments final Map<String, Resource> attachments = this.getAttachments(); if (attachments != null) { for (String attachmentName : attachments.keySet()) { helper.addAttachment(attachmentName, attachments.get(attachmentName)); } } }
From source file:gr.abiss.calipso.mail.MailSender.java
/** * /*from w ww . jav a 2 s. c o m*/ * @param email * @param subject * @param messageBody * @param attachments * @param encryption * @param keyStorePath */ public void send(String email, String subject, String messageBody, Map<String, DataSource> attachments, boolean html) { // prepare message try { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); if (html) { helper.setText(addHeaderAndFooter(messageBody), true); } else { helper.setText(messageBody, false); } helper.setSubject(subject); helper.setSentDate(new Date()); helper.setFrom(from); // set TO helper.setTo(email); if (MapUtils.isNotEmpty(attachments)) { for (String attachmentFilename : attachments.keySet()) { DataSource in = attachments.get(attachmentFilename); if (in != null) { helper.addAttachment(attachmentFilename, in); } } } //logger.info("Sending email: "+subject+"\n"+messageBody); sendInNewThread(message); } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }
From source file:MailSender.java
public void send(Item item) { // major: well, sender is null, so no email is going out...silently. Just a debug message. // this means that the initial configuration is not able to create a sender. // This control should no be here and the methods that handle jndi or configFile should throw a // ConfigurationException if the sender is not created. if (sender == null) { logger.debug("mail sender is null, not sending notifications"); return;//from www .j a v a 2s . c om } // TODO make this locale sensitive per recipient // major: don't use the comment to explain what the code is doing, just wrap the function in a // method with a talking name. This apply to all comments in this method. logger.debug("attempting to send mail for item update"); // prepare message content StringBuffer sb = new StringBuffer(); String anchor = getItemViewAnchor(item, defaultLocale); sb.append(anchor); // minor: why is not important here the user's locale like in the sendUserPassword method? sb.append(ItemUtils.getAsHtml(item, messageSource, defaultLocale)); sb.append(anchor); if (logger.isDebugEnabled()) { logger.debug("html content: " + sb); } // prepare message MimeMessage message = sender.createMimeMessage(); // minor: I would use StandardCharsets.UTF_8.name() that return the canonical name // major: how do you test the use cases about the message? // the message is in the local stack so it can't be tested // better to implement a bridge pattern to decouple the messageHelper and pass it as // a collaborator. Although keep in mind that building the message is not a responsibility // of this class so this class should just send the message and not building it. MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8"); // Remember the TO person email to prevent duplicate mails // minor: recipient would be a better name for this variable // major: catching a general Exception is a bad idea. You are telling me // we could have a problem but when I'm reading it and I don't understand // what could go wrong (and, also, the try block is too long so that's one of // the reason I can't see what could go wrong) String toPersonEmail; try { helper.setText(addHeaderAndFooter(sb), true); helper.setSubject(getSubject(item)); helper.setSentDate(new Date()); helper.setFrom(from); // set TO if (item.getAssignedTo() != null) { helper.setTo(item.getAssignedTo().getEmail()); toPersonEmail = item.getAssignedTo().getEmail(); } else { helper.setTo(item.getLoggedBy().getEmail()); toPersonEmail = item.getLoggedBy().getEmail(); } // set CC List<String> cclist = new ArrayList<String>(); if (item.getItemUsers() != null) { for (ItemUser itemUser : item.getItemUsers()) { // Send only, if person is not the TO assignee if (!toPersonEmail.equals(itemUser.getUser().getEmail())) { cclist.add(itemUser.getUser().getEmail()); } } // sounds complicated but we have to ensure that no null // item will be set in setCC(). So we collect the cc items // in the cclist and transform it to an stringarray. if (cclist.size() > 0) { String[] cc = cclist.toArray(new String[0]); helper.setCc(cc); } } // send message // workaround: Some PSEUDO user has no email address. Because email // address // is mandatory, you can enter "no" in email address and the mail // will not // be sent. // major: this check is too late, we created everything and then we // won't use it. if (!"no".equals(toPersonEmail)) sendInNewThread(message); } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }
From source file:info.jtrac.mail.MailSender.java
public void sendUserPassword(User user, String clearText) { if (sender == null) { logger.debug("mail sender is null, not sending new user / password change notification"); return;/*from w w w. j av a2 s .c o m*/ } logger.debug("attempting to send mail for user password"); String localeString = user.getLocale(); Locale locale = null; if (localeString == null) { locale = defaultLocale; } else { locale = StringUtils.parseLocaleString(localeString); } MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8"); try { helper.setTo(user.getEmail()); helper.setSubject(prefix + " " + fmt("loginMailSubject", locale)); StringBuffer sb = new StringBuffer(); sb.append("<p>" + fmt("loginMailGreeting", locale) + " " + user.getName() + ",</p>"); sb.append("<p>" + fmt("loginMailLine1", locale) + "</p>"); sb.append("<table class='jtrac'>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("loginName", locale) + "</th><td style='border: 1px solid black'>" + user.getLoginName() + "</td></tr>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("password", locale) + "</th><td style='border: 1px solid black'>" + clearText + "</td></tr>"); sb.append("</table>"); sb.append("<p>" + fmt("loginMailLine2", locale) + "</p>"); sb.append("<p><a href='" + url + "'>" + url + "</a></p>"); helper.setText(addHeaderAndFooter(sb), true); helper.setSentDate(new Date()); // helper.setCc(from); helper.setFrom(from); sendInNewThread(message); } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }
From source file:MailSender.java
public void sendUserPassword(User user, String clearText) { // major: well, sender is null, so no email is going out...silently. Just a debug message. // This means that the initial configuration is not able to create a sender. // This control should no be here and the methods that handle jndi or configFile should throw a // ConfigurationException if the sender is not created. if (sender == null) { logger.debug("mail sender is null, not sending new user / password change notification"); return;/*from www. j ava 2s. c om*/ } logger.debug("attempting to send mail for user password"); String localeString = user.getLocale(); Locale locale = null; if (localeString == null) { locale = defaultLocale; } else { locale = StringUtils.parseLocaleString(localeString); } // major: there is a bit of code duplication with the method send. // Apparently it seems that just the body is changing but the rest is // really similar. As suggested above the way a message is created should be // refactored in a collaborator. This method should just send a message. MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8"); try { helper.setTo(user.getEmail()); helper.setSubject(prefix + " " + fmt("loginMailSubject", locale)); StringBuffer sb = new StringBuffer(); sb.append("<p>" + fmt("loginMailGreeting", locale) + " " + user.getName() + ",</p>"); sb.append("<p>" + fmt("loginMailLine1", locale) + "</p>"); sb.append("<table class='jtrac'>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("loginName", locale) + "</th><td style='border: 1px solid black'>" + user.getLoginName() + "</td></tr>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("password", locale) + "</th><td style='border: 1px solid black'>" + clearText + "</td></tr>"); sb.append("</table>"); sb.append("<p>" + fmt("loginMailLine2", locale) + "</p>"); sb.append("<p><a href='" + url + "'>" + url + "</a></p>"); helper.setText(addHeaderAndFooter(sb), true); helper.setSentDate(new Date()); // helper.setCc(from); helper.setFrom(from); sendInNewThread(message); // major: generic exception, method too long, I don't understand what could fail. } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }
From source file:net.triptech.metahive.service.EmailSenderService.java
/** * Send an email message using the configured Spring sender. On success * record the sent message in the datastore for reporting purposes * * @param email the email/*from ww w. ja va2 s . c om*/ * @param attachments the attachments * @throws ServiceException the service exception */ public final void send(final SimpleMailMessage email, TreeMap<String, Object> attachments) throws ServiceException { // Check to see whether the required fields are set (to, from, message) if (email.getTo() == null) { throw new ServiceException("Error sending email: Recipient " + "address required"); } if (StringUtils.isBlank(email.getFrom())) { throw new ServiceException("Error sending email: Email requires " + "a from address"); } if (StringUtils.isBlank(email.getText())) { throw new ServiceException("Error sending email: No email " + "message specified"); } if (mailSender == null) { throw new ServiceException("The JavaMail sender has not " + "been configured"); } // Prepare the email message MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = null; boolean htmlMessage = false; if (StringUtils.containsIgnoreCase(email.getText(), "<html")) { htmlMessage = true; try { helper = new MimeMessageHelper(message, true, "UTF-8"); } catch (MessagingException me) { throw new ServiceException("Error preparing email for sending: " + me.getMessage()); } } else { helper = new MimeMessageHelper(message); } try { helper.setTo(email.getTo()); helper.setFrom(email.getFrom()); helper.setSubject(email.getSubject()); if (email.getCc() != null) { helper.setCc(email.getCc()); } if (email.getBcc() != null) { helper.setBcc(email.getBcc()); } if (htmlMessage) { String plainText = email.getText(); try { ConvertHtmlToText htmlToText = new ConvertHtmlToText(); plainText = htmlToText.convert(email.getText()); } catch (Exception e) { logger.error("Error converting HTML to plain text: " + e.getMessage()); } helper.setText(plainText, email.getText()); } else { helper.setText(email.getText()); } if (email.getSentDate() != null) { helper.setSentDate(email.getSentDate()); } else { helper.setSentDate(Calendar.getInstance().getTime()); } } catch (MessagingException me) { throw new ServiceException("Error preparing email for sending: " + me.getMessage()); } // Append any attachments (if an HTML email) if (htmlMessage && attachments != null) { for (String id : attachments.keySet()) { Object reference = attachments.get(id); if (reference instanceof File) { try { FileSystemResource res = new FileSystemResource((File) reference); helper.addInline(id, res); } catch (MessagingException me) { logger.error("Error appending File attachment: " + me.getMessage()); } } if (reference instanceof URL) { try { UrlResource res = new UrlResource((URL) reference); helper.addInline(id, res); } catch (MessagingException me) { logger.error("Error appending URL attachment: " + me.getMessage()); } } } } // Send the email message try { mailSender.send(message); } catch (MailException me) { logger.error("Error sending email: " + me.getMessage()); throw new ServiceException("Error sending email: " + me.getMessage()); } }
From source file:gr.abiss.calipso.mail.MailSender.java
public void sendUserPassword(User user, String clearText) { if (sender == null) { logger.warn("mail sender is null, not sending new user / password change notification"); return;//from w w w . j av a 2s . c o m } if (logger.isDebugEnabled()) { logger.debug("attempting to send mail for user password"); } Locale locale = getUserLocale(user); try { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); helper.setTo(user.getEmail()); helper.setSubject(prefix + " " + fmt("loginMailSubject", locale)); StringBuffer sb = new StringBuffer(); String greeting = fmt("loginMailGreeting", locale); if (org.apache.commons.lang.StringUtils.isNotBlank(greeting)) { sb.append("<p>" + fmt("loginMailGreeting", locale) + " " + user.getName() + ",</p>"); } sb.append("<p>" + fmt("loginMailLine1", locale) + "</p>"); sb.append("<table class='calipsoService'>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("loginName", locale) + ": </th><td style='border: 1px solid black'>" + user.getLoginName() + " </td></tr>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("password", locale) + ": </th><td style='border: 1px solid black'>" + clearText + " </td></tr>"); sb.append("</table>"); sb.append("<p>" + fmt("loginMailLine2", locale) + "</p>"); sb.append("<p><a href='" + url + "'>" + url + "</a></p>"); sb.append("<p>" + fmt("loginMailLine3", locale) + "</p>"); helper.setText(addHeaderAndFooter(sb), true); helper.setSentDate(new Date()); // helper.setCc(from); helper.setFrom(from); sendInNewThread(message); } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }
From source file:it.ozimov.springboot.templating.mail.utils.EmailToMimeMessage.java
@Override public MimeMessage apply(final Email email) { final MimeMessage mimeMessage = javaMailSender.createMimeMessage(); final MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, fromNullable(email.getEncoding()).or(Charset.forName("UTF-8")).displayName()); try {/*from w w w .ja va 2 s. c om*/ messageHelper.setFrom(email.getFrom()); if (ofNullable(email.getReplyTo()).isPresent()) { messageHelper.setReplyTo(email.getReplyTo()); } if (ofNullable(email.getTo()).isPresent()) { for (final InternetAddress address : email.getTo()) { messageHelper.addTo(address); } } if (ofNullable(email.getCc()).isPresent()) { for (final InternetAddress address : email.getCc()) { messageHelper.addCc(address); } } if (ofNullable(email.getBcc()).isPresent()) { for (final InternetAddress address : email.getBcc()) { messageHelper.addBcc(address); } } if (ofNullable(email.getAttachments()).isPresent()) { for (final EmailAttachmentImpl attachment : email.getAttachments()) { try { messageHelper.addAttachment(attachment.getAttachmentName(), attachment.getInputStream(), attachment.getContentType().getType()); } catch (IOException e) { log.error("Error while converting Email to MimeMessage"); throw new EmailConversionException(e); } } } messageHelper.setSubject(ofNullable(email.getSubject()).orElse("")); messageHelper.setText(ofNullable(email.getBody()).orElse("")); if (nonNull(email.getSentAt())) { messageHelper.setSentDate(email.getSentAt()); } } catch (MessagingException e) { log.error("Error while converting Email to MimeMessage"); throw new EmailConversionException(e); } return mimeMessage; }
From source file:com.sfs.dao.EmailMessageDAOImpl.java
/** * Send an email message using the configured Spring sender. On success * record the sent message in the datastore for reporting purposes * * @param emailMessage the email message * * @throws SFSDaoException the SFS dao exception *///w w w .j a v a2 s.c o m public final void send(final EmailMessageBean emailMessage) throws SFSDaoException { // Check to see whether the required fields are set (to, from, message) if (StringUtils.isBlank(emailMessage.getTo())) { throw new SFSDaoException("Error recording email: Recipient " + "address required"); } if (StringUtils.isBlank(emailMessage.getFrom())) { throw new SFSDaoException("Error recording email: Email requires " + "a return address"); } if (StringUtils.isBlank(emailMessage.getMessage())) { throw new SFSDaoException("Error recording email: No email " + "message specified"); } if (javaMailSender == null) { throw new SFSDaoException("The EmailMessageDAO has not " + "been configured"); } // Prepare the email message MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = null; if (emailMessage.getHtmlMessage()) { try { helper = new MimeMessageHelper(message, true, "UTF-8"); } catch (MessagingException me) { throw new SFSDaoException("Error preparing email for sending: " + me.getMessage()); } } else { helper = new MimeMessageHelper(message); } if (helper == null) { throw new SFSDaoException("The MimeMessageHelper cannot be null"); } try { if (StringUtils.isNotBlank(emailMessage.getTo())) { StringTokenizer tk = new StringTokenizer(emailMessage.getTo(), ","); while (tk.hasMoreTokens()) { String address = tk.nextToken(); helper.addTo(address); } } if (StringUtils.isNotBlank(emailMessage.getCC())) { StringTokenizer tk = new StringTokenizer(emailMessage.getCC(), ","); while (tk.hasMoreTokens()) { String address = tk.nextToken(); helper.addCc(address); } } if (StringUtils.isNotBlank(emailMessage.getBCC())) { StringTokenizer tk = new StringTokenizer(emailMessage.getBCC(), ","); while (tk.hasMoreTokens()) { String address = tk.nextToken(); helper.addBcc(address); } } if (StringUtils.isNotBlank(emailMessage.getFrom())) { if (StringUtils.isNotBlank(emailMessage.getFromName())) { try { helper.setFrom(emailMessage.getFrom(), emailMessage.getFromName()); } catch (UnsupportedEncodingException uee) { dataLogger.error("Error setting email from", uee); } } else { helper.setFrom(emailMessage.getFrom()); } } helper.setSubject(emailMessage.getSubject()); helper.setPriority(emailMessage.getPriority()); if (emailMessage.getHtmlMessage()) { final String htmlText = emailMessage.getMessage(); String plainText = htmlText; try { ConvertHtmlToText htmlToText = new ConvertHtmlToText(); plainText = htmlToText.convert(htmlText); } catch (Exception e) { dataLogger.error("Error converting HTML to plain text: " + e.getMessage()); } helper.setText(plainText, htmlText); } else { helper.setText(emailMessage.getMessage()); } helper.setSentDate(emailMessage.getSentDate()); } catch (MessagingException me) { throw new SFSDaoException("Error preparing email for sending: " + me.getMessage()); } // Append any attachments (if an HTML email) if (emailMessage.getHtmlMessage()) { for (String id : emailMessage.getAttachments().keySet()) { final Object reference = emailMessage.getAttachments().get(id); if (reference instanceof File) { try { FileSystemResource res = new FileSystemResource((File) reference); helper.addInline(id, res); } catch (MessagingException me) { dataLogger.error("Error appending File attachment: " + me.getMessage()); } } if (reference instanceof URL) { try { UrlResource res = new UrlResource((URL) reference); helper.addInline(id, res); } catch (MessagingException me) { dataLogger.error("Error appending URL attachment: " + me.getMessage()); } } } } // If not in debug mode send the email if (!debugMode) { deliver(emailMessage, message); } }