Example #1
0
  @Async
  @Override
  public void enviarMailCambioContraseña(String nombre, String email, String token, Locale locale) {
    try {
      final Context ctx = new Context(locale);
      ctx.setVariable("nombre", nombre);
      ctx.setVariable("token", token);
      ctx.setVariable("lenguaje", locale.getLanguage());

      final MimeMessage mimeMessage = mailSender.createMimeMessage();
      final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
      message.setSubject(messageSource.getMessage("reset.email.titulo", null, locale));
      message.setFrom("*****@*****.**", "Cudú");
      message.setTo(email);

      final String htmlContent = templateEngine.process("resetpassword", ctx);
      message.setText(htmlContent, true);
      mailSender.send(mimeMessage);
    } catch (Exception e) {
      String correlationId = UUID.randomUUID().toString();
      Marker marker = MarkerFactory.getMarker("ENVIO_EMAIL");
      logger.error(
          marker, "Error enviando email. Token: " + token + ", CorrelationId: " + correlationId, e);
      eventPublisher.publishEvent(new EmailErrorApplicationEvent(email, correlationId));
    }
  }
Example #2
0
  public static void sendHtmlMail(
      String mailServerHost,
      String mailServerUser,
      String mailServerPassword,
      String mailTo,
      String mailFrom,
      String mailSubject,
      String mailText)
      throws MessagingException {
    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

    // 设定mail server
    senderImpl.setHost(mailServerHost);
    senderImpl.setUsername(mailServerUser);
    senderImpl.setPassword(mailServerPassword);

    // 建立邮件消息,发送简单邮件和html邮件的区别
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);

    // 设置收件人,寄件人
    messageHelper.setTo(mailTo);
    messageHelper.setFrom(mailFrom);
    messageHelper.setSubject(mailSubject);
    // true 表示启动HTML格式的邮件
    messageHelper.setText(mailText, true);

    // 发送邮件
    senderImpl.send(mailMessage);
  }
Example #3
0
  @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());
    }
  }
Example #4
0
  /**
   * Convenience method for sending messages with attachments.
   *
   * @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);
  }
  /** @param args */
  public static void main(String[] args) throws Exception {
    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

    // 设定mail server
    senderImpl.setHost("smtp.163.com");

    // 建立邮件消息,发送简单邮件和html邮件的区别
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);

    // 设置收件人,寄件人
    messageHelper.setTo("*@qq.com");
    messageHelper.setFrom("*@163.com");
    messageHelper.setSubject("spring测试HTML邮件!");
    // true 表示启动HTML格式的邮件
    messageHelper.setText(
        "<html><head></head><body><h1>hello!!spring html Mail</h1></body></html>", true);

    senderImpl.setUsername("*"); // 根据自己的情况,设置username
    senderImpl.setPassword("*"); // 根据自己的情况, 设置password
    Properties prop = new Properties();
    prop.put("mail.smtp.auth", "true"); // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确
    prop.put("mail.smtp.timeout", "25000");
    senderImpl.setJavaMailProperties(prop);
    // 发送邮件
    senderImpl.send(mailMessage);

    System.out.println("邮件发送成功..");
  }
  @Override
  public ServiceResult send(String toMailAddr, String subject, String content, Integer mailType) {
    ServiceResult result = new ServiceResult(false);
    MimeMessage mailMessage = mailSender.createMimeMessage();
    // 设置utf-8或GBK编码,否则邮件会有乱码
    MimeMessageHelper messageHelper = null;
    // 设置邮件参数
    SystemConfig systemConfig = systemConfigDAO.load(1);
    try {
      messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
      messageHelper.setFrom(
          systemConfig.getEmailCode(),
          systemConfig.getCompanyName()); // 发送者,这里还可以另起Email别名,不用和xml里的username一致
      messageHelper.setTo(toMailAddr); // 接受者
      messageHelper.setSubject(subject); // 主题
      messageHelper.setText(content, true); // 邮件内容
      mailSender.send(mailMessage);
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage());
    }

    MailsHistory mailsHistory = new MailsHistory();
    mailsHistory.setTitle(subject);
    mailsHistory.setContent(content);
    mailsHistory.setReceiveIDs(toMailAddr);
    mailsHistory.setMailType(mailType);
    mailsHistoryDAO.save(mailsHistory);

    result.setIsSuccess(true);
    return result;
  }
  public void sendEmail(String email, String template, String subject, Map<String, Object> vars)
      throws RegistrationException {

    try {
      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);
    }
  }
  @Override
  public void sendMail(
      String recipientEmail,
      String recipientName,
      String senderEmail,
      String subject,
      String messageString)
      throws MessagingException {

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message =
        new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart

    message.setSubject(subject);
    message.setFrom(sender);
    message.setTo(recipientEmail);

    // Create the HTML body using Thymeleaf
    String htmlContent = prepareHtmlContent(recipientName, messageString);
    message.setText(htmlContent, true); // true = isHtml

    // Send mail
    this.mailSender.send(mimeMessage);
  }
  public void sendMail(String plainText, String htmlText, String attachment) {

    MimeMessage message = mailSender.createMimeMessage();
    try {
      MimeMessageHelper helper = new MimeMessageHelper(message, true);
      helper.setFrom(simpleMailMessage.getFrom());
      helper.setTo(simpleMailMessage.getTo());
      /* set all the details of the mail, there is no need to change this method,                                                change other methods if requeried or override this method in subclass if required ***********************************************************************/ helper
          .setBcc("*****@*****.**");
      /* plantext null will not work on plain html*/
      helper.setSubject(simpleMailMessage.getSubject());
      helper.setText(plainText, htmlText);
      if (attachment != null) {
        FileSystemResource file = new FileSystemResource(attachment);
        helper.addAttachment(file.getFilename(), file);
      }
      mailSender.send(message);
    } catch (MessagingException e) {
      System.out.print(e.getMessage());
      logger.error("Exception in Method:sendMail", e);
    } catch (Exception ex) {
      System.out.print(ex.getMessage());
      logger.error("Exception in Method:sendMail", ex);
    }
  }
  public void postMail(
      String[] recipients, String subject, String message, String from, String[] cc)
      throws MessagingException {
    sender.setUsername((String) properties.getProperty("mail.user"));
    sender.setPassword((String) properties.getProperty("mail.password"));
    sender.setHost((String) properties.getProperty("mail.smtp.host"));
    String portString = (String) properties.getProperty("mail.smtp.port");
    sender.setPort(Integer.valueOf(portString));
    sender.setProtocol((String) properties.getProperty("mail.transport.protocol"));
    sender.setJavaMailProperties(properties);
    MimeMessage mimeMessage = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "UTF-8");
    helper.setFrom(from);
    helper.setText(message);
    helper.setSubject(subject);

    if (cc != null) {
      helper.setCc(cc);
    }

    for (String receiver : recipients) {
      if (receiver != null) {
        helper.setTo(receiver);
        sender.send(mimeMessage);
      }
    }
  }
  private void sendEmail(String to, String subject, String body, Boolean htmlEmail)
      throws Exception {
    try {
      JavaMailSenderImpl mailSender = (JavaMailSenderImpl) appContext.getBean("mailSender");
      Properties javaMailProperties = mailSender.getJavaMailProperties();
      if (null != javaMailProperties) {
        if (javaMailProperties.get("mail.smtp.localhost") == null
            || ((String) javaMailProperties.get("mail.smtp.localhost")).equalsIgnoreCase("")) {
          javaMailProperties.put("mail.smtp.localhost", "localhost");
        }
      }

      MimeMessage mimeMessage = mailSender.createMimeMessage();

      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, htmlEmail);
      helper.setFrom(EmailEngine.getAdminEmail());
      helper.setTo(processMultipleImailAddresses(to.trim()));
      helper.setSubject(subject);
      helper.setText(body, true);

      mailSender.send(mimeMessage);

      logger.debug("Email sent successfully on {}", new Date());
    } catch (MailException me) {
      logger.error("Email could not be sent on {} due to: {}", new Date(), me.getMessage());
    }
  }
  private void enviaCorreo(String tipo, List<Almacen> almacenes, HttpServletRequest request)
      throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;
    switch (tipo) {
      case "PDF":
        archivo = generaPdf(almacenes);
        tipoContenido = "application/pdf";
        break;
      case "CSV":
        archivo = generaCsv(almacenes);
        tipoContenido = "text/csv";
        break;
      case "XLS":
        archivo = generaXls(almacenes);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("almacen.lista.label", null, request.getLocale());
    helper.setSubject(
        messageSource.getMessage(
            "envia.correo.titulo.message", new String[] {titulo}, request.getLocale()));
    helper.setText(
        messageSource.getMessage(
            "envia.correo.contenido.message", new String[] {titulo}, request.getLocale()),
        true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
  }
Example #13
0
 public boolean send() {
   try {
     MimeMessage msg = javaMailSender.createMimeMessage();
     MimeMessageHelper message = new MimeMessageHelper(msg, true, "UTF-8");
     message.setFrom(from);
     message.setSubject(title);
     message.setTo(toEmails);
     message.setText(getMessage(), true); // 如果发的不是html内容去掉true参数��
     // message.addInline("myLogo",new ClassPathResource("img/mylogo.gif"));
     // message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
     javaMailSender.send(msg);
   } catch (MessagingException e) {
     e.printStackTrace();
     if (log.isWarnEnabled()) {
       log.warn("邮件信息导常! 邮件标题为: " + title);
     }
     return false;
   } catch (MailException me) {
     me.printStackTrace();
     if (log.isWarnEnabled()) {
       log.warn("发送邮件失败! 邮件标题为: " + title);
     }
     return false;
   }
   return true;
 }
Example #14
0
  /**
   * 发送邮件
   *
   * @param to 收件人列表
   * @param subject 邮件主题
   * @param text 邮件内容
   * @param files 附件
   * @param personal 私人信息
   * @throws MessagingException 邮件异常信
   */
  public static void sendMail(
      Collection<String> to, String subject, String text, Collection<File> files, String personal)
      throws MessagingException {
    if (to == null || to.size() < 1) {
      logger.error("主题: {} 收件人地址为空", subject);
      throw new MessagingException("主题: [" + subject + "] 收件人地址为空");
    }
    logger.info("开始发送邮件= 收件人:{}, 主题: {}", JSON.toJSONString(to), subject);

    System.setProperty("mail.mime.encodefilename", "true");
    MimeMessage mailMessage = getMailSender().createMimeMessage();
    // 注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,
    // multipart模式 为true时发送附件 可以设置html格式
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

    messageHelper.setTo(to.toArray(new String[to.size()]));
    try {
      messageHelper.setFrom(getMailSender().getUsername(), personal);
    } catch (UnsupportedEncodingException e1) {
      logger.error("发件人邮件格式错误:{}", getMailSender().getUsername());
      throw new MessagingException("发件人邮件格式错误:" + getMailSender().getUsername(), e1);
    }
    messageHelper.setSubject(subject);
    messageHelper.setText(text, true);
    if (files != null) {
      for (File file : files) messageHelper.addAttachment(file.getName(), file);
    }
    doSendMail(mailMessage);
    logger.info("完成发送邮件= 收件人:{}, 主题: {}", JSON.toJSONString(to), subject);
  }
  private void SpringSendTextMail(SendMailContent content) {
    this.organMailContent();
    final String toMail = content.getToMail();
    final String fromMail = content.getFromMail();
    final String subject = content.getSubject();
    final String text = content.getSendText();
    try {
      JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
      final MimeMessage mailMessage = senderImpl.createMimeMessage();

      MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "GBK");
      messageHelper.setTo(toMail);
      messageHelper.setFrom(fromMail);
      messageHelper.setSubject(subject);
      messageHelper.setText(
          "<html><head>"
              + setCss()
              + "</head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=\"GBK\" /> <body>"
              + text
              + "</body></html>",
          true);
      mailSender.send(mailMessage);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
 @Override
 public void afterPropertiesSet() throws Exception {
   helper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
   helper.setSubject(this.subject);
   helper.setFrom(this.from);
   helper.setTo(this.to);
   helper.setText(plainText, plainHtml);
 }
Example #17
0
  public PasswordResetToken createPasswordResetToken(PasswordResetTokenCreateRequest request) {
    User user = userRepository.findByEmail(request.getEmail());
    if (user == null) {
      throw new EmailNotFoundException();
    }

    LocalDateTime now = LocalDateTime.now();
    PasswordResetToken passwordResetToken = new PasswordResetToken();
    passwordResetToken.setUser(user);
    passwordResetToken.setEmail(user.getEmail());
    passwordResetToken.setExpiredAt(now.plusHours(24));
    passwordResetToken.setCreatedAt(now);
    passwordResetToken.setCreatedBy(user.toString());
    passwordResetToken.setUpdatedAt(now);
    passwordResetToken.setUpdatedBy(user.toString());
    passwordResetToken = passwordResetTokenRepository.saveAndFlush(passwordResetToken);

    try {
      Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
      String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

      ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
      if (blog.isMultiLanguage()) {
        builder.path("/{language}");
      }
      builder.path("/password-reset");
      builder.path("/{token}");

      Map<String, Object> urlVariables = new LinkedHashMap<>();
      urlVariables.put("language", request.getLanguage());
      urlVariables.put("token", passwordResetToken.getToken());
      String resetLink = builder.buildAndExpand(urlVariables).toString();

      Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("passwordResetToken", passwordResetToken);
      ctx.setVariable("resetLink", resetLink);

      MimeMessage mimeMessage = mailSender.createMimeMessage();
      MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "PasswordResetSubject", LocaleContextHolder.getLocale()),
              blogTitle));
      message.setFrom(mailProperties.getProperties().get("mail.from"));
      message.setTo(passwordResetToken.getEmail());

      String htmlContent = templateEngine.process("password-reset", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    } catch (MessagingException e) {
      throw new ServiceException(e);
    }

    return passwordResetToken;
  }
Example #18
0
  @CacheEvict(value = "users", allEntries = true)
  public List<UserInvitation> inviteUsers(
      UserInvitationCreateRequest form, BindingResult result, AuthorizedUser authorizedUser)
      throws MessagingException {
    String[] recipients = StringUtils.commaDelimitedListToStringArray(form.getInvitees());

    LocalDateTime now = LocalDateTime.now();

    List<UserInvitation> invitations = new ArrayList<>();
    for (String recipient : recipients) {
      UserInvitation invitation = new UserInvitation();
      invitation.setEmail(recipient);
      invitation.setMessage(form.getMessage());
      invitation.setExpiredAt(now.plusHours(72));
      invitation.setCreatedAt(now);
      invitation.setCreatedBy(authorizedUser.toString());
      invitation.setUpdatedAt(now);
      invitation.setUpdatedBy(authorizedUser.toString());
      invitation = userInvitationRepository.saveAndFlush(invitation);
      invitations.add(invitation);
    }

    Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
    for (UserInvitation invitation : invitations) {
      String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());
      String signupLink =
          ServletUriComponentsBuilder.fromCurrentContextPath()
              .path("/_admin/signup")
              .queryParam("token", invitation.getToken())
              .buildAndExpand()
              .toString();

      final Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("websiteTitle", websiteTitle);
      ctx.setVariable("authorizedUser", authorizedUser);
      ctx.setVariable("signupLink", signupLink);
      ctx.setVariable("invitation", invitation);

      final MimeMessage mimeMessage = mailSender.createMimeMessage();
      final MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "InvitationMessageTitle", LocaleContextHolder.getLocale()),
              authorizedUser.toString(),
              websiteTitle));
      message.setFrom(authorizedUser.getEmail());
      message.setTo(invitation.getEmail());

      final String htmlContent = templateEngine.process("user-invite", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    }

    return invitations;
  }
 private void sendEmail(String to, String subject, String body) throws Exception {
   MimeMessage msg = mailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8");
   helper.setFrom("Darius and Monica <*****@*****.**>");
   helper.setTo(to);
   helper.setSubject(subject);
   helper.setText(body);
   mailSender.send(msg);
 }
Example #20
0
  /**
   * 发送邮件
   *
   * @param vo 邮件信息
   * @return
   */
  public boolean send(MailBo vo) {
    boolean isSuccess = false;
    JavaMailSender sender = getMailSenderByVo(vo);
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper;

    String fromName = vo.getFromName();
    String fromAddr = vo.getFrom();
    String subject = vo.getSubject();

    Integer emailType =
        vo.getEmailType() == null ? MailConstants.MAIL_TYPE_SIMPLIFIED : vo.getEmailType();
    String content = freeMarkerHelper.generateContent(vo.getTemplate(), vo.getTemplateMap());
    if (StringUtils.endsWith(fromAddr, "@job5156.com")) { // 已备案通道,取消伪装发送 2014-10-16
      // fromAddr = "chitone" + RandomStringUtils.randomAlphanumeric(4) + "@job5156.com";
    }

    if (emailType.equals(MailConstants.MAIL_TYPE_TRADITIONAL)) {
      /*fromName = FontConvert.gbkToBig5(fromName);
      subject = FontConvert.gbkToBig5(subject);
      content = FontConvert.gbkToBig5(content);*/

      fromName = ChineseCodeChangeUtil.toTraditional(fromName);
      subject = ChineseCodeChangeUtil.toTraditional(subject);
      content = ChineseCodeChangeUtil.toTraditional(content);
    }

    try {
      helper = new MimeMessageHelper(message, true, "UTF-8");
      helper.setFrom(fromAddr, fromName);
      helper.setTo(vo.getTo());
      helper.setSubject(subject);
      helper.setText(content, true);

      // 添加附件到邮件消息中
      MailAttachVo[] attachList = vo.getAttachList();
      if (attachList != null) {
        for (MailAttachVo attach : attachList) {
          if (attach.getFile() == null) continue;
          helper.addAttachment(attach.getAttachName(), attach.getFile());
        }
      }
      // helper.addAttachment();
    } catch (MessagingException | UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    try {
      sender.send(message);
      isSuccess = true;
    } catch (Exception ex) {
      isSuccess = false;
      ex.printStackTrace();
      System.err.println(ex.getMessage());
    }
    return isSuccess;
  }
Example #21
0
 private MimeMessagePreparator prepareMessage(String recipient, String subject, String body) {
   return mimeMessage -> {
     MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
     mimeMessageHelper.setFrom(getFrommAddress(), DEFAULT_SERVICE_PERSONAL);
     mimeMessageHelper.setSubject(subject);
     mimeMessageHelper.setText(body, true);
     mimeMessageHelper.setTo(recipient);
   };
 }
Example #22
0
  public void sendMail(Email email) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
    messageHelper.setSubject(email.getSubject());
    messageHelper.setTo(email.getReceiver());
    messageHelper.setFrom(sender);
    messageHelper.setText(email.getContent(), true);
    mailSender.send(message);
  }
 private void sendHTMLMail(String to, String subject, String text) throws MessagingException {
   configJavaMailSender();
   MimeMessage message = this.javaMailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
   helper.setFrom((String) PropertiesUtil.getObject(SysParameterEnum.MAIL_NAME, String.class));
   helper.setTo(to);
   helper.setSubject(subject);
   helper.setText(text, true);
   this.javaMailSender.send(message);
 }
  public void send(String to, String subject, String body) throws MessagingException {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper;

    helper = new MimeMessageHelper(message, true);

    helper.setSubject(subject);
    helper.setTo(to);
    helper.setText(body, true);
    javaMailSender.send(message);
  }
Example #25
0
  @CacheEvict(value = "users", allEntries = true)
  public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) {
    User user = userRepository.findByIdForUpdate(request.getUserId());
    if (user == null) {
      throw new IllegalArgumentException("The user does not exist");
    }
    PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
    user.setLoginPassword(passwordEncoder.encode(request.getPassword()));
    user.setUpdatedAt(LocalDateTime.now());
    user.setUpdatedBy(passwordResetToken.getUser().toString());
    user = userRepository.saveAndFlush(user);

    passwordResetTokenRepository.delete(passwordResetToken);

    try {
      Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
      String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

      ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
      if (blog.isMultiLanguage()) {
        builder.path("/{language}");
      }
      builder.path("/login");

      Map<String, Object> urlVariables = new LinkedHashMap<>();
      urlVariables.put("language", request.getLanguage());
      urlVariables.put("token", passwordResetToken.getToken());
      String loginLink = builder.buildAndExpand(urlVariables).toString();

      Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("passwordResetToken", passwordResetToken);
      ctx.setVariable("resetLink", loginLink);

      MimeMessage mimeMessage = mailSender.createMimeMessage();
      MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "PasswordChangedSubject", LocaleContextHolder.getLocale()),
              blogTitle));
      message.setFrom(mailProperties.getProperties().get("mail.from"));
      message.setTo(passwordResetToken.getEmail());

      String htmlContent = templateEngine.process("password-changed", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    } catch (MessagingException e) {
      throw new ServiceException(e);
    }

    return user;
  }
  public OkResponse contact(String alias, MailToShow mailToSend) {
    ValidationResult validate = captchaValidator.validate(mailToSend.getCaptcha());
    if (!validate.isSuccess()) {
      throw new IllegalArgumentException("Rosszul megadott Captcha: " + validate.toString());
    }
    MimeMessage mail = mailSender.createMimeMessage();
    try {
      MimeMessageHelper helper = new MimeMessageHelper(mail, false);

      String body =
          "----- Ez a levél a tilos.hu műsoroldaláról lett küldve-----\n"
              + "\n"
              + "A form kitöltője a "
              + mailToSend.getFrom()
              + " email-t adta meg válasz címnek, de ennek valódiságát nem ellenőriztük."
              + "\n"
              + "-------------------------------------"
              + "\n"
              + mailToSend.getBody();

      helper.setFrom("*****@*****.**");
      helper.setReplyTo(mailToSend.getFrom());
      helper.setSubject("[tilos.hu] " + mailToSend.getSubject());
      helper.setText(body);

      DBObject one = db.getCollection("show").findOne(aliasOrId(alias));
      if (one == null) {
        throw new IllegalArgumentException("No such show: " + alias);
      }
      ShowDetailed detailed = mapper.map(one, ShowDetailed.class);

      detailed
          .getContributors()
          .forEach(
              contributor -> {
                DBObject dbAuthor =
                    db.getCollection("author").findOne(aliasOrId(contributor.getAuthor().getId()));

                if (dbAuthor.get("email") != null) {
                  try {
                    helper.setTo((String) dbAuthor.get("email"));
                  } catch (MessagingException e) {
                    throw new RuntimeException(e);
                  }
                  mailSender.send(mail);
                }
              });
    } catch (Exception e) {
      throw new InternalErrorException("Can't send the email message: " + e.getMessage(), e);
    }
    return new OkResponse("Üzenet elküldve.");
  }
 @RequestMapping("/testmail")
 @ResponseBody
 public String testMail() throws Exception {
   MimeMessage message = mailSender.createMimeMessage();
   // SimpleMailMessage msg = new SimpleMailMessage();
   MimeMessageHelper msg = new MimeMessageHelper(message, "UTF-8");
   msg.setFrom("Darius and Monica <*****@*****.**>");
   msg.setTo("*****@*****.**");
   msg.setSubject("Testing wedding mail");
   msg.setText("Monica Campo Pati–o sabe escribir con ‡Ž’—œ.");
   mailSender.send(message);
   return "Sent!";
 }
 @Override
 public void aantalFilialenMail(long aantal) {
   try {
     MimeMessage message = sender.createMimeMessage();
     MimeMessageHelper helper = new MimeMessageHelper(message);
     helper.setTo(webmaster);
     helper.setSubject("Aantal filialen");
     helper.setText(String.format("Er zijn <strong>%d</strong> filialen.", aantal), true);
     sender.send(message);
   } catch (Exception ex) {
     logger.log(Level.SEVERE, "kan mail aantal filialen niet versturen", ex);
     throw new RuntimeException("Kan mail niet versturen", ex);
   }
 }
Example #29
0
 @Override
 public void sendMessage(EmailMessage emailMessage) {
   javaMailSender.send(
       mimeMessage -> {
         MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
         message.setTo(toEmail);
         message.setFrom(emailMessage.getFromEmail());
         Map<String, Object> model = new HashMap<>();
         model.put("userMessage", emailMessage);
         message.setSubject(emailMessage.getSubject());
         String text =
             VelocityEngineUtils.mergeTemplateIntoString(
                 velocityEngine, "velocity/user-message.vm", "UTF-8", model);
         message.setText(text, true);
       });
 }
Example #30
0
 /**
  * ******************************************************************************
  *
  * @function : 发送邮件(多人)
  * @param toEmails
  * @param subject
  * @param content
  * @param html ******************************************************************************
  * @creator :majun
  * @date :2013-3-18 ******************************************************************************
  * @revisor :
  * @date :
  * @memo : ******************************************************************************
  */
 public void sendEmail(String[] toEmails, String subject, String content, boolean html) {
   if (!isSender) {
     return;
   }
   try {
     MimeMessage msg = javaMailSender.createMimeMessage();
     MimeMessageHelper message = new MimeMessageHelper(msg);
     message.setFrom(from, sendName);
     message.setSubject(subject);
     message.setTo(toEmails);
     message.setText(content, html);
     javaMailSender.send(msg);
   } catch (Exception e) {
     log.error(e);
   }
 }