List of usage examples for org.springframework.mail.javamail MimeMessageHelper setFrom
public void setFrom(String from) throws MessagingException
From source file:org.syncope.core.scheduling.NotificationJob.java
public TaskExec executeSingle(final NotificationTask task) { init();/*ww w. j a v a2s .co m*/ 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:eu.trentorise.smartcampus.citizenportal.service.EmailService.java
public void sendMailWithInline(final String recipientName, final String recipientEmail, final String imageResourceName, final byte[] imageBytes, final String imageContentType, final Locale locale) throws MessagingException { // Prepare the evaluation context final Context ctx = new Context(locale); ctx.setVariable("name", recipientName); ctx.setVariable("subscriptionDate", new Date()); ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music")); ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML // Prepare message using a Spring helper final MimeMessage mimeMessage = this.mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8"); message.setSubject("Example HTML email with inline image"); message.setFrom("thymeleaf@example.com"); message.setTo(recipientEmail);//from w ww . j av a 2 s . c o m // Create the HTML body using Thymeleaf final String htmlContent = this.templateEngine.process("email-inlineimage.html", ctx); message.setText(htmlContent, true /* isHtml */); // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}" final InputStreamSource imageSource = new ByteArrayResource(imageBytes); message.addInline(imageResourceName, imageSource, imageContentType); // Send mail this.mailSender.send(mimeMessage); }
From source file:gr.abiss.calipso.service.EmailService.java
@Async public void sendMailWithAttachment(final String recipientName, final String recipientEmail, final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType, final Locale locale) throws MessagingException { // Prepare the evaluation context final Context ctx = new Context(locale); ctx.setVariable("name", recipientName); ctx.setVariable("subscriptionDate", new Date()); ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music")); // Prepare message using a Spring helper final MimeMessage mimeMessage = this.mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8"); message.setSubject("Example HTML email with attachment"); message.setFrom("thymeleaf@example.com"); message.setTo(recipientEmail);//from w ww .java 2 s .co m // Create the HTML body using Thymeleaf final String htmlContent = this.templateEngine.process("email-withattachment.html", ctx); LOGGER.info("Sending email body: " + htmlContent); message.setText(htmlContent, true /* isHtml */); // Add the attachment final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes); message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType); // Send mail this.mailSender.send(mimeMessage); }
From source file:gr.abiss.calipso.service.EmailService.java
@Async public void sendMailWithInline(final String recipientName, final String recipientEmail, final String imageResourceName, final byte[] imageBytes, final String imageContentType, final Locale locale) throws MessagingException { // Prepare the evaluation context final Context ctx = new Context(locale); ctx.setVariable("name", recipientName); ctx.setVariable("subscriptionDate", new Date()); ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music")); ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML // Prepare message using a Spring helper final MimeMessage mimeMessage = this.mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8"); message.setSubject("Example HTML email with inline image"); message.setFrom("thymeleaf@example.com"); message.setTo(recipientEmail);//from w w w.j a v a2s . c o m // Create the HTML body using Thymeleaf final String htmlContent = this.templateEngine.process("email-inlineimage.html", ctx); LOGGER.info("Sending email body: " + htmlContent); message.setText(htmlContent, true /* isHtml */); // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}" final InputStreamSource imageSource = new ByteArrayResource(imageBytes); message.addInline(imageResourceName, imageSource, imageContentType); // Send mail this.mailSender.send(mimeMessage); }
From source file:eionet.meta.service.EmailServiceImpl.java
/** * {@inheritDoc}/*w ww.java 2s. c o m*/ */ @Override public void notifySiteCodeReservation(String userName, int startIdentifier, int reserveAmount) throws ServiceException { try { SiteCodeAddedNotification notification = new SiteCodeAddedNotification(); notification.setCreatedTime(new Date().toString()); notification.setUsername(userName); notification.setNewCodesStartIdentifier(Integer.toString(startIdentifier)); notification.setNofAddedCodes(Integer.toString(reserveAmount)); notification.setNewCodesEndIdentifier(Integer.toString(startIdentifier + reserveAmount - 1)); notification.setTotalNumberOfAvailableCodes(Integer.toString(siteCodeDao.getFeeSiteCodeAmount())); final String[] to; // if test e-mail is provided, then do not send notification to actual receivers if (!StringUtils.isEmpty(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO))) { notification.setTest(true); notification.setTo(Props.getRequiredProperty(PropsIF.SITE_CODE_RESERVE_NOTIFICATION_TO)); to = StringUtils.split(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO), ","); } else { to = StringUtils.split(Props.getRequiredProperty(PropsIF.SITE_CODE_RESERVE_NOTIFICATION_TO), ","); } Map<String, Object> map = new HashMap<String, Object>(); map.put("data", notification); final String text = processTemplate("site_code_reservation.ftl", map); MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false); message.setText(text, false); message.setFrom( new InternetAddress(Props.getRequiredProperty(PropsIF.SITE_CODE_NOTIFICATION_FROM))); message.setSubject("New site codes added"); message.setTo(to); } }; mailSender.send(mimeMessagePreparator); } catch (Exception e) { throw new ServiceException("Failed to send new site codes reservation notification: " + e.toString(), e); } }
From source file:eu.trentorise.smartcampus.citizenportal.service.EmailService.java
public String sendSimpleMail(final String recipientName, final String recipientEmail, final String subject, final Locale locale) throws MessagingException { // Prepare the evaluation context final Context ctx = new Context(locale); ctx.setVariable("name", recipientName); ctx.setVariable("subscriptionDate", new Date()); //ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music")); ctx.setVariable("text", subject); // Prepare message using a Spring helper final MimeMessage mimeMessage = this.mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8"); message.setSubject("Graduatoria Edilizia Abitativa"); //message.setFrom("thymeleaf@example.com"); message.setFrom("myweb.edilizia@comunitadellavallagarina.tn.it"); message.setTo(recipientEmail);/* w w w . j a v a 2 s.com*/ // Create the HTML body using Thymeleaf final String htmlContent = this.templateEngine.process("email-simple.html", ctx); message.setText(htmlContent, true /* isHtml */); // Send email this.mailSender.send(mimeMessage); return recipientName; }
From source file:com.epam.ta.reportportal.util.email.EmailService.java
/** * Builds FROM field/*ww w. j a v a2s .co m*/ * If username is email, format will be "from \<email\>" */ private void setFrom(MimeMessageHelper message) throws MessagingException, UnsupportedEncodingException { if (!Strings.isNullOrEmpty(this.from)) { if (isAddressValid(this.from)) { message.setFrom(this.from); } else if (UserUtils.isEmailValid(getUsername())) { message.setFrom(getUsername(), this.from); } } //otherwise generate automatically }
From source file:cz.zcu.kiv.eegdatabase.data.service.SpringJavaMailService.java
@Override public void sendNotification(String email, ArticleComment comment, Locale locale) throws MailException { try {/*from w w w .jav a 2s . c om*/ String articleURL = "http://" + domain + "/articles/detail.html?articleId=" + comment.getArticle().getArticleId(); //System.out.println(articleURL); String subject = messageSource.getMessage("articles.comments.email.subscribtion.subject", new String[] { comment.getArticle().getTitle(), comment.getPerson().getUsername() }, locale); //System.out.println(subject); String emailBody = "<html><body>"; emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part1", new String[] { comment.getArticle().getTitle() }, locale) + ""; emailBody += " (<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL + "</a>)</p><br />"; emailBody += "<h3>Text:</h3> <p>" + comment.getText() + "</p><br />"; emailBody += "<p>" + messageSource.getMessage("articles.group.email.subscribtion.body.text.part2", null, locale) + "</p>"; emailBody += "</body></html>"; //System.out.println(emailBody); log.debug("email body: " + emailBody); log.debug("Composing e-mail message"); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setFrom(mailMessage.getFrom()); // message.setContent("text/html"); message.setTo(email); //helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request))); message.setSubject(subject); message.setText(emailBody, true); log.debug("Sending e-mail" + message); log.debug("mailSender" + mailSender); mailSender.send(mimeMessage); log.debug("E-mail was sent"); } catch (MailException e) { log.error("E-mail for subscribers was NOT sent"); log.error(e.getMessage(), e); } catch (MessagingException e) { log.error("E-mail for subscribers was NOT sent"); log.error(e.getMessage(), e); } }
From source file:eionet.meta.service.EmailServiceImpl.java
/** * {@inheritDoc}/*from w w w. j a va 2s .co m*/ */ @Override public void notifySiteCodeAllocation(String country, AllocationResult allocationResult, boolean adminRole) throws ServiceException { try { SiteCodeAllocationNotification notification = new SiteCodeAllocationNotification(); notification.setAllocationTime(allocationResult.getAllocationTime().toString()); notification.setUsername(allocationResult.getUserName()); notification.setCountry(country); notification.setNofAvailableCodes(Integer.toString(siteCodeDao.getFeeSiteCodeAmount())); notification.setTotalNofAllocatedCodes( Integer.toString(siteCodeDao.getCountryUnusedAllocations(country, false))); notification.setNofCodesAllocatedByEvent(Integer.toString(allocationResult.getAmount())); SiteCodeFilter filter = new SiteCodeFilter(); filter.setDateAllocated(allocationResult.getAllocationTime()); filter.setUserAllocated(allocationResult.getUserName()); filter.setUsePaging(false); SiteCodeResult siteCodes = siteCodeDao.searchSiteCodes(filter); notification.setSiteCodes(siteCodes.getList()); notification.setAdminRole(adminRole); final String[] to; // if test e-mail is provided, then do not send notification to actual receivers if (!StringUtils.isEmpty(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO))) { notification.setTest(true); notification.setTo(StringUtils.join(parseRoleAddresses(country), ",")); to = StringUtils.split(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO), ","); } else { to = parseRoleAddresses(country); } Map<String, Object> map = new HashMap<String, Object>(); map.put("data", notification); final String text = processTemplate("site_code_allocation.ftl", map); MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false); message.setText(text, false); message.setFrom( new InternetAddress(Props.getRequiredProperty(PropsIF.SITE_CODE_NOTIFICATION_FROM))); message.setSubject("Site codes allocated"); message.setTo(to); } }; mailSender.send(mimeMessagePreparator); } catch (Exception e) { throw new ServiceException("Failed to send allocation notification: " + e.toString(), e); } }
From source file:cz.zcu.kiv.eegdatabase.data.service.SpringJavaMailService.java
@Override public void sendNotification(String email, Article article, Locale locale) { try {//from ww w .jav a2 s.co m String articleURL = "http://" + domain + "/articles/detail.html?articleId=" + article.getArticleId(); // System.out.println(articleURL); String subject = messageSource.getMessage("articles.group.email.subscribtion.subject", new String[] { article.getTitle(), article.getPerson().getUsername() }, locale); // System.out.println(subject); String emailBody = "<html><body>"; emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part1", new String[] { article.getTitle(), article.getResearchGroup() != null ? article.getResearchGroup().getTitle() : "Public articles" }, locale) + ""; emailBody += " (<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL + "</a>)</p><br />"; emailBody += "<h3>" + article.getTitle() + "</h3> <p>" + article.getText() + "</p><br />"; emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part2", null, locale) + "</p>"; emailBody += "</body></html>"; // System.out.println(emailBody); log.debug("email body: " + emailBody); log.debug("Composing e-mail message"); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setFrom(mailMessage.getFrom()); // message.setContent("text/html"); message.setTo(email); // helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request))); message.setSubject(subject); message.setText(emailBody, true); log.debug("Sending e-mail" + message); log.debug("mailSender" + mailSender); mailSender.send(mimeMessage); log.debug("E-mail was sent"); } catch (MailException e) { log.error("E-mail for subscribers was NOT sent"); log.error(e.getMessage(), e); } catch (MessagingException e) { log.error("E-mail for subscribers was NOT sent"); log.error(e.getMessage(), e); } }