List of usage examples for org.springframework.mail.javamail MimeMessageHelper MimeMessageHelper
public MimeMessageHelper(MimeMessage mimeMessage, int multipartMode, @Nullable String encoding) throws MessagingException
From source file:eu.trentorise.smartcampus.permissionprovider.manager.MailSender.java
public void sendEmail(String email, String template, String subject, Map<String, Object> vars) throws RegistrationException { try {//from w w w .j a v a2 s . com final Context ctx = new Context(); if (vars != null) { for (String var : vars.keySet()) { ctx.setVariable(var, vars.get(var)); } } final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); message.setSubject(subject); message.setFrom(mailUser); message.setTo(email); // Create the HTML body using Thymeleaf final String htmlContent = this.templateEngine.process(template, ctx); message.setText(htmlContent, true); // Send mail mailSender.send(mimeMessage); } catch (Exception e) { e.printStackTrace(); throw new RegistrationException(e); } }
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 *//*from w w w. j a va 2 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); } }
From source file:com.aurora.mail.service.MailService.java
/** * @param to//from w w w .j a v a2 s. c o m * @param subject * @param content * @param isMultipart * @param isHtml */ @Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send e-mail to user '{}'!", to); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8); message.setTo(to); message.setFrom(from); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent e-mail to user '{}'!", to); } catch (Exception e) { log.error("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage()); } }
From source file:net.groupbuy.service.impl.MailServiceImpl.java
public void send(String smtpFromMail, String smtpHost, Integer smtpPort, String smtpUsername, String smtpPassword, String toMail, String subject, String templatePath, Map<String, Object> model, boolean async) { Assert.hasText(smtpFromMail);/*from ww w . j a v a 2 s . c o m*/ Assert.hasText(smtpHost); Assert.notNull(smtpPort); Assert.hasText(smtpUsername); Assert.hasText(smtpPassword); Assert.hasText(toMail); Assert.hasText(subject); Assert.hasText(templatePath); try { Setting setting = SettingUtils.get(); Configuration configuration = freeMarkerConfigurer.getConfiguration(); Template template = configuration.getTemplate(templatePath); String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); javaMailSender.setHost(smtpHost); javaMailSender.setPort(smtpPort); javaMailSender.setUsername(smtpUsername); javaMailSender.setPassword(smtpPassword); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8"); mimeMessageHelper.setFrom(MimeUtility.encodeWord(setting.getSiteName()) + " <" + smtpFromMail + ">"); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setTo(toMail); mimeMessageHelper.setText(text, true); if (async) { addSendTask(mimeMessage); } else { javaMailSender.send(mimeMessage); } } catch (TemplateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } }
From source file:com.rxx.common.util.MailUtil.java
/** * html// w w w . j av a 2s . c om * * @param host * @param port * @param userName * @param password * @param title * @param contenthtml * @param toUser * @throws javax.mail.MessagingException */ public static void sendHtml(String host, int port, String userName, String password, String title, String content, String[] toUser) { JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); // mail server senderImpl.setHost(host); senderImpl.setPort(port); // ,html MimeMessage mailMessage = senderImpl.createMimeMessage(); try { MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "UTF-8"); try { // messageHelper.setTo(toUser); messageHelper.setFrom(userName); messageHelper.setSubject(title); // true HTML messageHelper.setText(content, true); } catch (javax.mail.MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } senderImpl.setUsername(userName); // ,username senderImpl.setPassword(password); // , password Properties prop = new Properties(); prop.put("mail.smtp.auth", "true"); // true, prop.put("mail.smtp.timeout", "25000"); senderImpl.setJavaMailProperties(prop); // senderImpl.send(mailMessage); } catch (javax.mail.MessagingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
From source file:com.epam.ta.reportportal.util.email.EmailService.java
/** * User creation confirmation email/*from w w w . j a v a2s.c o m*/ * * @param subject Letter's subject * @param recipients Letter's recipients * @param url ReportPortal URL */ public void sendConfirmationEmail(final String subject, final String[] recipients, final String url) { MimeMessagePreparator preparator = mimeMessage -> { URL logoImg = this.getClass().getClassLoader().getResource(LOGO); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8"); message.setSubject(subject); message.setTo(recipients); setFrom(message); Map<String, Object> email = new HashMap<>(); email.put("url", url); String text = templateEngine.merge("registration-template.vm", email); message.setText(text, true); message.addInline("logoimg", new UrlResource(logoImg)); }; this.send(preparator); }
From source file:com.github.dactiv.fear.service.service.message.MessageService.java
/** * ??/*from w w w . j a v a 2 s. c o m*/ * * @param nickname ?? null * @param mail */ private void doSendMail(String nickname, Mail mail) { try { JavaMailSender mailSender = getJavaMailSender(); if (mailSender == null) { throw new ServiceException("???"); } MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper; if (mailSender instanceof JavaMailSenderImpl) { JavaMailSenderImpl jmsi = (JavaMailSenderImpl) mailSender; helper = new MimeMessageHelper(msg, true, jmsi.getDefaultEncoding()); } else { helper = new MimeMessageHelper(msg, true); } helper.setTo(mail.getTo()); helper.setFrom(getSendForm(nickname, mailSender)); helper.setSubject(mail.getTitle()); helper.setText(mail.getContent(), mail.getHtml()); if (!MapUtils.isEmpty(mail.getAttachment())) { for (Map.Entry<String, File> entry : mail.getAttachment().entrySet()) { helper.addAttachment(entry.getKey(), entry.getValue()); } } mailSender.send(msg); LOGGER.info("???"); } catch (Exception e) { LOGGER.error("??", e); } }
From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java
public void sendMailNotification(ReportExecutionJob job, ReportJob jobDetails, List reportOutputs) throws JobExecutionException { ReportJobMailNotification mailNotification = jobDetails.getMailNotification(); if (mailNotification != null) { try {//from w w w. j av a 2s . c om // skip mail notification when job fails if (mailNotification.isSkipNotificationWhenJobFails() && (!job.exceptions.isEmpty())) { return; } JavaMailSender mailSender = job.getMailSender(); String fromAddress = job.getFromAddress(); MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, job.getCharacterEncoding()); messageHelper.setFrom(fromAddress); messageHelper.setSubject(mailNotification.getSubject()); StringBuffer messageText = new StringBuffer(); addMailRecipients(mailNotification, messageHelper); boolean isEmailBodyOccupied = false; if (reportOutputs != null && !reportOutputs.isEmpty()) { byte resultSendType = jobDetails.getMailNotification().getResultSendType(); if ((resultSendType == ReportJobMailNotification.RESULT_SEND_EMBED) || (resultSendType == ReportJobMailNotification.RESULT_SEND_EMBED_ZIP_ALL_OTHERS)) { List attachmentReportList = new ArrayList(); for (Iterator it = reportOutputs.iterator(); it.hasNext();) { ReportOutput output = (ReportOutput) it.next(); if ((!isEmailBodyOccupied) && output.getFileType().equals(ContentResource.TYPE_HTML) && (job.exceptions.isEmpty())) { // only embed html output embedOutput(messageHelper, output); isEmailBodyOccupied = true; } else if (resultSendType == ReportJobMailNotification.RESULT_SEND_EMBED) { // save the rest of the output as attachments attachOutput(job, messageHelper, output, (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT)); } else { // RESULT_SEND_EMBED_ZIP_ALL_OTHERS attachmentReportList.add(output); } } if (attachmentReportList.size() > 0) { // put the rest of attachments in 1 zip file attachOutputs(job, messageHelper, attachmentReportList); } } else if (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT || resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT_NOZIP) { for (Iterator it = reportOutputs.iterator(); it.hasNext();) { ReportOutput output = (ReportOutput) it.next(); attachOutput(job, messageHelper, output, (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT)); } } else if (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT_ZIP_ALL) { // put all the attachments in 1 zip file attachOutputs(job, messageHelper, reportOutputs); } else { appendRepositoryLinks(job, messageText, reportOutputs); } } if (mailNotification.isIncludingStackTraceWhenJobFails()) { if (!job.exceptions.isEmpty()) { for (Iterator it = job.exceptions.iterator(); it.hasNext();) { ExceptionInfo exception = (ExceptionInfo) it.next(); messageText.append("\n"); messageText.append(exception.getMessage()); attachException(messageHelper, exception); } } } String text = mailNotification.getMessageText(); if (!job.exceptions.isEmpty()) { if (mailNotification.getMessageTextWhenJobFails() != null) text = mailNotification.getMessageTextWhenJobFails(); else text = job.getMessage("report.scheduling.job.default.mail.notification.message.on.fail", null); } if (!isEmailBodyOccupied) messageHelper.setText(text + "\n" + messageText.toString()); mailSender.send(message); } catch (MessagingException e) { log.error("Error while sending report job result mail", e); throw new JSExceptionWrapper(e); } } }
From source file:org.icgc.dcc.release.client.mail.Mailer.java
@SneakyThrows private void sendFailed(String templateName, Map<String, ?> of, Exception e) { // TODO: Format nicely val message = new MimeMessageHelper(mailSender.createMimeMessage(), true, UTF_8.name()); message.setSubject(createSubject(templateName)); message.setText(e.toString(), true); message.setTo(mail.getRecipients()); mailSender.send(message.getMimeMessage()); }
From source file:org.apache.niolex.commons.mail.EmailUtil.java
/** * Send an email.// w w w . j a v a 2 s . c o m * ???? * * @param from the email sender * @param tos the email receivers array * @param ccs the carbon copiers array * @param title the email title * @param text the email body * @param attachments the email attachments list * @param priority priority from 1-5 the smaller is higher * @param isHtml is the text in HTML format or not * @param encoding the encoding of email, i.e. "GBK"?"UTF-8" * @throws MailException * @throws MessagingException */ public static void sendMail(String from, String[] tos, String[] ccs, String title, String text, List<Pair<String, InputStreamSource>> attachments, String priority, boolean isHtml, String encoding) throws MailException, MessagingException { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, encoding); messageHelper.setFrom(from); messageHelper.setBcc(from); if (ArrayUtils.isEmpty(tos)) { throw new IllegalArgumentException("<tos> can not be null or empty!"); } else { messageHelper.setTo(tos); } if (!ArrayUtils.isEmpty(ccs)) { messageHelper.setCc(ccs); } messageHelper.setSubject(title); messageHelper.setText(text, isHtml); if (attachments != null) { for (Pair<String, InputStreamSource> pair : attachments) { messageHelper.addAttachment(pair.a, pair.b); } } mimeMessage = messageHelper.getMimeMessage(); if (priority != null) { mimeMessage.addHeader("X-Priority", priority); } mailSender.send(mimeMessage); }