List of usage examples for org.springframework.mail.javamail MimeMessageHelper setSubject
public void setSubject(String subject) throws MessagingException
From source file:de.metas.procurement.webui.service.impl.LoginService.java
@Override public void sendPasswordResetKey(final String email, final URI passwordResetURI) { Preconditions.checkNotNull(passwordResetURI, "passwordResetURI is null"); MimeMessage mail = emailSender.createMimeMessage(); try {//from w ww .j a v a2 s .co m MimeMessageHelper helper = new MimeMessageHelper(mail, true); // multipart=true if (emailFrom != null && !emailFrom.trim().isEmpty()) { helper.setFrom(emailFrom.trim()); } helper.setTo(email); helper.setSubject(i18n.get("PasswordReset.email.subject")); helper.setText(i18n.get("PasswordReset.email.content", passwordResetURI)); } catch (MessagingException e) { e.printStackTrace(); } finally { } emailSender.send(mail); }
From source file:com.hygenics.parser.Send.java
public void run() { try {// www . ja v a2s . c om log.info("Creating Message"); MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); InternetAddress addr = new InternetAddress(fromEmails); helper.setFrom(addr); for (String email : emails) { helper.addTo(new InternetAddress(email)); } helper.setSubject(subject); helper.setText(body); if (fpath != null) { log.info("Attaching File"); File f = new File(fpath); if (f.exists()) { helper.addAttachment(fpath, f); } } log.info("Sending Email"); mailSender.send(message); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.appverse.web.framework.backend.api.services.integration.impl.live.MailIntegrationServiceImpl.java
@SuppressWarnings("unchecked") @Override/*from w w w.ja va 2 s .c om*/ public void sendMail(String from, String[] to, String[] copyTo, String subject, String templateLocation, Map model, ArrayList<AttachmentDTO> attachments) throws Exception { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); if (copyTo != null) { helper.setCc(copyTo); } helper.setSubject(subject); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, ENCODING, templateLocation, model); helper.setText(text, true); for (AttachmentDTO attachmentDTO : attachments) { helper.addAttachment(attachmentDTO.getAttachmentName(), attachmentDTO.getAttachment()); } try { this.mailSender.send(message); } catch (MailSendException sendMailException) { Exception[] messageExceptions = sendMailException.getMessageExceptions(); for (Exception messageException : messageExceptions) { if (messageException instanceof SendFailedException) { SendFailedException sendFailedException = (SendFailedException) messageException; if (sendFailedException.getMessage().equals(INVALID_ADDRESSES)) { Address[] invalidAddresses = sendFailedException.getInvalidAddresses(); List<String> invalidAddressList = new ArrayList<String>(); for (Address invalidAddress : invalidAddresses) { String invalidAddressString = invalidAddress.toString(); invalidAddressList.add(invalidAddressString); } List<String> validToAdressesList = new ArrayList<String>(); if (to != null && to.length > 0) { for (String address : to) { if (!invalidAddressList.contains(address)) { validToAdressesList.add(address); } } } List<String> validCopyToAdressesList = new ArrayList<String>(); if (copyTo != null && copyTo.length > 0) { for (String address : copyTo) { if (!invalidAddressList.contains(address)) { validCopyToAdressesList.add(address); } } } String[] validToAdressesArray = new String[validToAdressesList.size()]; validToAdressesList.toArray(validToAdressesArray); helper.setTo(validToAdressesList.toArray(validToAdressesArray)); String[] validCopyToAdressesArray = new String[validCopyToAdressesList.size()]; validCopyToAdressesList.toArray(validCopyToAdressesArray); helper.setCc(validCopyToAdressesList.toArray(validCopyToAdressesArray)); for (String invalidAddress : invalidAddressList) { logger.error("Mail not sended to " + invalidAddress + "due its a invalid address"); } this.mailSender.send(message); } } } } }
From source file:no.dusken.common.control.MailController.java
/** * * @param mail the mail part of the mail * @param model other things that should be in the mail. * @param template - the path to the velocitytemplate to use (mail/template.vm) *//*from ww w.j av a2 s .co m*/ public void sendEmail(final Mail mail, final Map model, final String template) { final Map<String, Object> map = new HashMap<String, Object>(); if (model != null) { map.putAll(model); } MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(mail.getToAddress()); if (mail.getFromAddress() == null || mail.getFromAddress().equals("")) { mail.setFromAddress(defaultSenderAddress); } message.setFrom(mail.getFromAddress()); message.setSubject(mail.getSubject()); map.put("mail", mail); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, map); message.setText(text, false); if (mail.getAttachment() != null) { FileSystemResource res = new FileSystemResource(mail.getAttachment()); message.addAttachment(mail.getAttachment().getName(), res); } } }; this.mailSender.send(preparator); }
From source file:ar.com.zauber.commons.message.impl.mail.MimeEmailNotificationStrategy.java
/** @see NotificationStrategy#execute(NotificationAddress[], Message) */ public final void execute(final NotificationAddress[] addresses, final Message message) { try {/*from ww w .j a v a 2s . com*/ final MailSender mailSender = getMailSender(); //This is ugly....but if it is not a JavaMailSender it will //fail (for instance during tests). And the only way to //create a Multipartemail is through JavaMailSender if (mailSender instanceof JavaMailSender) { final JavaMailSender javaMailSender = (JavaMailSender) mailSender; final MimeMessage mail = javaMailSender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(mail, true); helper.setFrom(getFromAddress().getEmailStr()); helper.setTo(SimpleEmailNotificationStrategy.getEmailAddresses(addresses)); helper.setReplyTo(getEmailAddress(message.getReplyToAddress())); helper.setSubject(message.getSubject()); setContent(helper, (MultipartMessage) message); addHeaders(message, mail); javaMailSender.send(mail); } else { final SimpleMailMessage mail = new SimpleMailMessage(); mail.setFrom(getFromAddress().getEmailStr()); mail.setTo(getEmailAddresses(addresses)); mail.setReplyTo(getEmailAddress(message.getReplyToAddress())); mail.setSubject(message.getSubject()); mail.setText(message.getContent()); mailSender.send(mail); } } catch (final MessagingException e) { throw new RuntimeException("Could not send message", e); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("Could not send message", e); } }
From source file:info.jtrac.mail.MailSender.java
public void send(Item item) { if (sender == null) { logger.debug("mail sender is null, not sending notifications"); return;// w ww. ja v a 2 s . co m } // TODO make this locale sensitive per recipient logger.debug("attempting to send mail for item update"); // prepare message content StringBuffer sb = new StringBuffer(); String anchor = getItemViewAnchor(item, defaultLocale); sb.append(anchor); sb.append(ItemUtils.getAsHtml(item, messageSource, defaultLocale)); sb.append(anchor); if (logger.isDebugEnabled()) { logger.debug("html content: " + sb); } // prepare message MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8"); 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()); } else { helper.setTo(item.getLoggedBy().getEmail()); } // set CC if (item.getItemUsers() != null) { String[] cc = new String[item.getItemUsers().size()]; int i = 0; for (ItemUser itemUser : item.getItemUsers()) { cc[i++] = itemUser.getUser().getEmail(); } helper.setCc(cc); } // send message sendInNewThread(message); } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }
From source file:org.musicrecital.service.MailEngine.java
/** * Convenience method for sending messages with attachments. * //from w w w.ja v a 2 s. c o m * @param recipients array of e-mail addresses * @param sender e-mail address of sender * @param resource attachment from classpath * @param bodyText text in e-mail * @param subject subject of e-mail * @param attachmentName name for attachment * @throws MessagingException thrown when can't communicate with SMTP server */ public void sendMessage(String[] recipients, String sender, ClassPathResource resource, String bodyText, String subject, String attachmentName) throws MessagingException { MimeMessage message = ((JavaMailSenderImpl) mailSender).createMimeMessage(); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(recipients); // use the default sending if no sender specified if (sender == null) { helper.setFrom(defaultFrom); } else { helper.setFrom(sender); } helper.setText(bodyText); helper.setSubject(subject); helper.addAttachment(attachmentName, resource); ((JavaMailSenderImpl) mailSender).send(message); }
From source file:org.syncope.core.scheduling.NotificationJob.java
public TaskExec executeSingle(final NotificationTask task) { init();/* w w w. j a v a 2 s .c om*/ TaskExec execution = new TaskExec(); execution.setTask(task); execution.setStartDate(new Date()); if (StringUtils.isBlank(smtpHost) || StringUtils.isBlank(task.getSender()) || StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty() || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) { String message = "Could not fetch all required information for " + "sending e-mails:\n" + smtpHost + ":" + smtpPort + "\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody(); LOG.error(message); execution.setStatus(Status.NOT_SENT.name()); if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) { execution.setMessage(message); } } else { if (LOG.isDebugEnabled()) { LOG.debug("About to send e-mails:\n" + smtpHost + ":" + smtpPort + "\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody() + "\n"); } for (String to : task.getRecipients()) { try { JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost(smtpHost); sender.setPort(smtpPort); if (StringUtils.isNotBlank(smtpUsername)) { sender.setUsername(smtpUsername); } if (StringUtils.isNotBlank(smtpPassword)) { sender.setPassword(smtpPassword); } MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setFrom(task.getSender()); helper.setSubject(task.getSubject()); helper.setText(task.getTextBody(), task.getHtmlBody()); sender.send(message); execution.setStatus(Status.SENT.name()); StringBuilder report = new StringBuilder(); switch (task.getTraceLevel()) { case ALL: report.append("FROM: ").append(task.getSender()).append('\n').append("TO: ").append(to) .append('\n').append("SUBJECT: ").append(task.getSubject()).append('\n') .append('\n').append(task.getTextBody()).append('\n').append('\n') .append(task.getHtmlBody()).append('\n'); break; case SUMMARY: report.append("E-mail sent to ").append(to).append('\n'); break; case FAILURES: case NONE: default: } if (report.length() > 0) { execution.setMessage(report.toString()); } } catch (Throwable t) { LOG.error("Could not send e-mail", t); execution.setStatus(Status.NOT_SENT.name()); StringWriter exceptionWriter = new StringWriter(); exceptionWriter.write(t.getMessage() + "\n\n"); t.printStackTrace(new PrintWriter(exceptionWriter)); if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) { execution.setMessage(exceptionWriter.toString()); } } execution.setEndDate(new Date()); } } if (hasToBeRegistered(execution)) { execution = taskExecDAO.save(execution); } return execution; }
From source file:com.cfitzarl.cfjwed.service.impl.EmailDispatchingServiceImpl.java
/** {@inheritDoc} **/ @Override/*from w w w . ja va2 s . c o m*/ public void send(String to, String subject, String template, Map<String, Object> attrs) { // Add message source decorator to attributes list for localization attrs.put("localeSource", localizationService); String htmlFilename = String.format("/email-templates/%s-html.vm", template); String textFilename = String.format("/email-templates/%s-text.vm", template); String htmlContent = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, htmlFilename, "UTF-8", attrs); String textContent = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, textFilename, "UTF-8", attrs); try { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); String fromEmail = configDao.findByKey(ConfigKey.EMAIL).getValue(); String fromTitle = configDao.findByKey(ConfigKey.TITLE).getValue(); String from = String.format("%s <%s>", fromTitle, fromEmail); helper.setTo(to); helper.setSubject(subject); helper.setFrom(from); helper.setReplyTo(from); helper.setText(textContent, htmlContent); taskExecutor.submit(new MailRunner(message, javaMailSender)); } catch (MessagingException e) { LOGGER.error("Error generating mail message", e); } }
From source file:br.com.s2it.snakes.controllers.CarController.java
@RequestMapping("/email") public void email() { try {//from w w w . j a va 2 s . co m MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage); mailMsg.setFrom("snakeshackathon@gmail.com"); mailMsg.setTo("daniel@balieiro.com"); mailMsg.setSubject("Test mail"); mailMsg.setText("Hello World!"); mailSender.send(mimeMessage); } catch (Exception e) { e.printStackTrace(); } }