/** * {@inheritDoc} */ @Async @Override public void sendMailWithUsername( @NotBlank @Email final String email, @NotBlank final String username ) { log.info("Called with e-mail {}, username {}", email, username); try { final JavaMailSenderImpl sender = new JavaMailSenderImpl(); final MimeMessage message = sender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(email); helper.setSubject("Recover username"); helper.setText("Your username: " + "<b>" + username + "</b>", true); sendMail(message); } catch (MessagingException e) { e.printStackTrace(); } }
@Override public void sendWithAttachment(String to, String subject, String templateName, Map<String, String> data, InputStream attachment, String attachmentName) { LOG.debug("Sending email from {} to {} with subject {}", from, to, subject); MimeMessagePreparator messagePreparator = message -> { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setFrom(from); helper.setSubject(subject); helper.setText(templateService.createTemplate(templateName, data)); helper.addAttachment(attachmentName, new ByteArrayResource(IOUtils.toByteArray(attachment))); }; mailSender.send(messagePreparator); IOUtils.closeQuietly(attachment); }
void sendEmail(String to, String subject, String content, String from) { log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", false, true, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, CharEncoding.UTF_8); message.setTo(to); message.setFrom(from); message.setSubject(subject); message.setText(content, true); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } catch (Exception e) { if (log.isDebugEnabled()) { log.warn("Email could not be sent to user '{}'", to, e); } else { log.warn("Email could not be sent to user '{}': {}", to, e.getMessage()); } } }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // 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(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } catch (Exception e) { log.warn("Email could not be sent to user '{}'", to, e); } }
@Override public void sendEmail(final UserDTO user, String url) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(user.getEmail()); message.setSubject(SUBJECT); message.setFrom(EMAIL_FROM); // could be parameterized... Map model = new HashMap(); model.put("user", user); model.put("url", url); String text = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, "org/enricogiurin/sushibar/registration-confirmation.vm", model); message.setText(text, true); } }; this.emailSender.send(preparator); }
@Async public void sendPasswordResetMail(String target,String reseturl,JavaMailSender javaMailSender) throws InterruptedException { try { MimeMessage mimeMsg = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, false, "utf-8"); String content = (String) PropertyPlaceholder.getProperty("mail.template"); content = content.replace("{reseturl}", reseturl); helper.setText(content, true); helper.setTo(new String[]{target}); String title = (String) PropertyPlaceholder.getProperty("mail.title"); helper.setSubject(title); String authormail = (String) PropertyPlaceholder.getProperty("mail.sendfrom"); String authorname = (String) PropertyPlaceholder.getProperty("mail.sendname"); helper.setFrom(authormail,authorname); javaMailSender.send(mimeMsg); log.info("Password Reset Mail has been send to "+target); } catch(Exception e) { e.printStackTrace(); } }
@Override public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException { MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(mailParameters.getToMailAddress()); message.setFrom(mailParameters.getFromMailAddress()); message.setSubject(mailParameters.getSubject()); if (mailParameters.hasCcMailAddress()) { message.setCc(mailParameters.getCcMailAddress()); } if (mailParameters.hasReplyTo()) { message.setReplyTo(mailParameters.getReplyTo()); } String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties()); log.debug("*** TEST text='" + text + "'"); message.setText(text, true); message.setValidateAddresses(true); } }; this.mailSender.send(preparator); }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // 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(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } catch (Exception e) { if (log.isDebugEnabled()) { log.warn("Email could not be sent to user '{}'", to, e); } else { log.warn("Email could not be sent to user '{}': {}", to, e.getMessage()); } } }
/** * {@inheritDoc} */ @Async @Override public void sendMailWithNewPassword( @NotBlank @Email final String email, @NotBlank final String newPassword ) { log.info("Called with e-mail {}, newPassword {}", email, newPassword); try { final JavaMailSenderImpl sender = new JavaMailSenderImpl(); final MimeMessage message = sender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(email); helper.setSubject("Recover password"); helper.setText("Your new password: " + "<b>" + newPassword + "</b>", true); sendMail(message); } catch (MessagingException e) { e.printStackTrace(); } }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // 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(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent e-mail to User '{}'", to); } catch (Exception e) { log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage()); } }
private void sendMail(Optional<MimeMessageHelper> oMessage, MailType emailType) throws EmailNotSentException { String recipient = null; try { if (oMessage.isPresent()) { // TODO: don't assume that the "to" email field has at least one address recipient = oMessage.get().getMimeMessage().getRecipients(Message.RecipientType.TO)[0].toString(); if (!this.enabled) { LOG.info("Skipping sending email type {} to {} with body: {}", emailType, recipient, oMessage.get().getMimeMessage().getContent()); return; } LOG.info("Sending email type {} to {}", emailType, recipient); this.javaMailService.send(oMessage.get().getMimeMessage()); } else { throw new Exception(); } } catch (Exception e) { LOG.error("CRITICAL: error sending email type {} to {}. Reason {}", emailType, recipient, e.toString()); throw new EmailNotSentException(e); } }
private Optional<MimeMessageHelper> prepareMessage(Optional<MimeMessage> oMimeMessage, String recipient, String subject, MailType emailType) throws EmailNotPreparedException { Optional<MimeMessageHelper> oMessage = Optional.empty(); try { if (oMimeMessage.isPresent()) { oMessage = Optional.ofNullable(new MimeMessageHelper(oMimeMessage.get(), true, "UTF-8")); if (oMessage.isPresent()) { MimeMessageHelper message = oMessage.get(); message.setSubject(subject); message.setFrom(this.sendfrom); message.setTo(recipient); if ((this.enableBccToConfirmationEmail && emailType.equals(MailType.CONFIRMATION_EMAIL)) || (this.enableBccToSummaryEmail && emailType.equals(MailType.SUMMARY_EMAIL))) { message.setBcc(this.admin); } } } } catch (MessagingException e) { LOG.error("Error building the message of email type {} to {}", emailType, recipient); throw new EmailNotPreparedException(e); } return oMessage; }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // 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(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent e-mail to User '{}'", to); } catch (Exception e) { log.warn("E-mail could not be sent to user '{}'", to, e); } }
@Override public void sendEmail(@NonNull final Mail _mail, @NonNull final String _body, @Nullable final String _attachmentFilename, @Nullable final byte[] _pdfAttachment) { try { // Prepare message using a Spring helper final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, (_pdfAttachment != null), StandardCharsets.UTF_8.name()); message.setSubject("Tifoon Scan Report"); message.setFrom(_mail.getSender()); message.setTo(_mail.getRecipient()); message.setText(_body, true); if (_attachmentFilename != null && _pdfAttachment != null) { message.addAttachment(_attachmentFilename, new ByteArrayResource(_pdfAttachment)); } // Send mail mailSender.send(mimeMessage); } catch (MessagingException _e) { log.error("Failed to send e-mail", _e); } }
/** * To send email. * * @param mailParam its map containing mail headers details. i.e. "from" */ public void sendEmail(EmailDTO emailDTO) { try { if (Objects.nonNull(emailDTO)) { MimeMessage mail = javaMailSenderImpl.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mail, true); helper.setSubject(emailDTO.getSubject()); helper.setText(emailDTO.getMessage(), true); helper.setFrom(emailDTO.getFrom(), configurationService.getMailConfiguration().getFrom()); helper.setTo(emailDTO.getTo()); if (Objects.nonNull(emailDTO.getAttachment())) { helper.addAttachment(emailDTO.getAttachmentName(), emailDTO.getAttachment()); } javaMailSenderImpl.send(mail); } } catch (MessagingException | MailException | UnsupportedEncodingException e) { logger.error("Exception while sending mail notification.", e); } }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // 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(mailFromDisplay); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } catch (Exception e) { if (log.isDebugEnabled()) { log.warn("Email could not be sent to user '{}'", to, e); } else { log.warn("Email could not be sent to user '{}': {}", to, e.getMessage()); } } }
private void sendNotificationInternal(String email, String sipId, String result, Instant created, String templateName) { try { DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm"); DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd. MM. yyyy"); MimeMessageHelper message = generalMessage(email, appName, false); Map<String, Object> params = generalArguments(); params.put("sipId", sipId); params.put("result", result); params.put("createdDate", Utils.extractDate(created).format(dateFormatter)); params.put("createdTime", Utils.extractTime(created).format(timeFormatter)); InputStream template = Utils.resource(templateName); transformAndSend(template, params, message); } catch (MessagingException | IOException ex) { throw new GeneralException(ex); } }
protected MimeMessageHelper generalMessage(String emailTo, @Nullable String subject, boolean hasAttachment) throws MessagingException { MimeMessage message = sender.create(); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, hasAttachment); if (emailTo != null) { helper.setTo(emailTo); } if (subject != null) { helper.setSubject(subject); } try { helper.setFrom(senderEmail, senderName); } catch (UnsupportedEncodingException ex) { log.warn("Can not set email 'from' encoding, fallbacking."); helper.setFrom(senderEmail); } return helper; }
protected void transformAndSend(InputStream template, Map<String, Object> arguments, MimeMessageHelper helper) throws MessagingException, IOException { if (!enabled) { log.warn("Mail message was silently consumed because mail system is disabled."); return; } String text = templater.transform(template, arguments); helper.setText(text, true); MimeMessage message = helper.getMimeMessage(); if (message.getAllRecipients() != null && message.getAllRecipients().length > 0) { sender.send(message); } else { log.warn("Mail message was silently consumed because there were no recipients."); } }
/** * creates a activation mail. * * may throw a RuntimeException if no MimeMessage can be created * * @param activation {@link PendingAccountActivation} has to contain an id and an UisUser. UisUser should contain an mail address. * @return {@link MimeMessage} */ private MimeMessage createActivationMail(PendingAccountActivation activation) throws RuntimeException{ log.info("creating activation mail for pending activation"); MimeMessage mimeMsg = mailSender.createMimeMessage(); MimeMessageHelper msg = new MimeMessageHelper(mimeMsg, "UTF-8"); try { msg.setTo(activation.getForUser().getEmail()); msg.setSubject(messages.get(MAIL_SUBJECT)); msg.setText(messageContent(activation), true); } catch (MessagingException e) { log.warn("activation message creation FAILED! throwing runtime-exception now"); throw new RuntimeException(e); } return msg.getMimeMessage(); }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // 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(jHipsterProperties.getMailgun().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent e-mail to User '{}'", to); } catch (Exception e) { log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage()); } }
@Override public void run() { if (null != mailMessage) { MimeMessage mimeMsg = mailSender.createMimeMessage(); try { // 设置true,表示支持附件 MimeMessageHelper msgHelper = new MimeMessageHelper(mimeMsg, true, "UTF-8"); msgHelper.setFrom(mailMessage.getFromUser(), mailMessage.getCompanyName()); msgHelper.setSubject(mailMessage.getSubject()); String[] toArray = new String[mailMessage.getReceiveUsers().size()]; msgHelper.setTo(mailMessage.getReceiveUsers().toArray(toArray)); msgHelper.setText(mailMessage.getContent(), true); mailSender.send(mimeMsg); } catch (Exception e) { LOGGER.error("Send mail failed. Error message : {}", e.getMessage()); } } }
/** * 发送html邮件 */ @Async("mailAsync") public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); helper.setSentDate(new Date()); mailSender.send(message); logger.info("html邮件发送成功"); } catch (MessagingException e) { logger.error("发送html邮件时发生异常!", e); } }
/** * 发送带附件的邮件 */ @Async("mailAsync") public void sendAttachmentsMail(String to, String subject, String content, String filePath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); helper.setSentDate(new Date()); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } }
/** * 发送正文中有静态资源(图片)的邮件 */ @Async("mailAsync") public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); helper.setSentDate(new Date()); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); logger.info("嵌入静态资源的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送嵌入静态资源的邮件时发生异常!", e); } }
@Override public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException { final String subject = env.getProperty(type.getSubject()); final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName()); MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(recipient.getEmail()); helper.setSubject(subject); helper.setText(text); if (StringUtils.hasLength(attachment)) { helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes())); } mailSender.send(message); log.info("{} email notification has been send to {}", type, recipient.getEmail()); }
@Override public boolean sendEmail(final List<String> emails, final String subject, final String body) { if (emails == null || emails.isEmpty()) { return false; } asyncExecute(new Runnable() { public void run() { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper msg = new MimeMessageHelper(mimeMessage); msg.setTo(emails.toArray(new String[0])); msg.setSubject(subject); msg.setFrom(Config.SUPPORT_EMAIL); msg.setText(body, true); // body is assumed to be HTML } }; try { mailSender.send(preparator); logger.debug("Email sent to {}, {}", emails, subject); } catch (MailException ex) { logger.error("Failed to send email. {}", ex.getMessage()); } } }); return true; }
@Override public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); // html 格式的内容 mailSender.send(message); log.info("邮件发送成功!"); } catch (MessagingException e) { log.error("邮件发送失败!"); log.error("失败原因:{}", e); } }
@Override public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); log.info("邮件发送成功!"); } catch (MessagingException e) { log.error("邮件发送失败!"); log.error("失败原因:{}", e); } }