Ejemplo n.º 1
0
  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();
    }
  }
Ejemplo n.º 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);
  }
Ejemplo n.º 3
0
  @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;
  }
Ejemplo n.º 4
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));
    }
  }
Ejemplo n.º 5
0
  @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);
  }
Ejemplo n.º 6
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());
    }
  }
Ejemplo n.º 7
0
  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());
    }
  }
  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);
    }
  }
Ejemplo n.º 9
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;
 }
Ejemplo n.º 10
0
  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);
  }
  /** @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 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);
 }
Ejemplo n.º 13
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;
  }
Ejemplo n.º 14
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;
  }
Ejemplo n.º 15
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);
   };
 }
Ejemplo n.º 16
0
 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);
 }
Ejemplo n.º 17
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);
  }
Ejemplo n.º 18
0
 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);
  }
Ejemplo n.º 20
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;
  }
Ejemplo n.º 21
0
 @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!";
 }
Ejemplo n.º 22
0
 @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);
   }
 }
Ejemplo n.º 23
0
  public void mail(
      String aTo,
      String aSubject,
      String aMessage,
      Map<HeaderType, String> aHeaders,
      Map<String, byte[]> aAttachments)
      throws MessagingException {
    Validate.notEmpty(aTo, "The receiver must be specified.");
    Validate.notEmpty(aSubject, "The subject must be specified.");
    Validate.notEmpty(aMessage, "The message cannot be empty.");

    MimeMessage message = m_MailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setFrom(m_From);
    helper.setSubject(aSubject);
    helper.setText(aMessage);

    setHelperMethod(addTo, aTo, helper);

    if (aHeaders != null)
      for (HeaderType headerType : aHeaders.keySet()) {
        Validate.notEmpty(
            aHeaders.get(headerType),
            "The value attached to headers key " + headerType + " cannot be empty.");

        if (HeaderType.CC.equals(headerType))
          setHelperMethod(addCC, aHeaders.get(headerType), helper);

        if (HeaderType.BCC.equals(headerType))
          setHelperMethod(addBCC, aHeaders.get(headerType), helper);
      }

    if (aAttachments != null)
      for (String attachmentName : aAttachments.keySet()) {
        Validate.notEmpty(attachmentName, "All attachments must have a non empty name");
        Validate.isTrue(
            aAttachments.get(attachmentName).length > 0,
            "The content of attachment " + attachmentName + " cannot be empty.");

        helper.addAttachment(
            attachmentName, new ByteArrayResource(aAttachments.get(attachmentName)));
      }

    log.info("Sending message " + aSubject + " to " + aTo);

    m_MailSender.send(message);
  }
Ejemplo n.º 24
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);
       });
 }
Ejemplo n.º 25
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);
   }
 }
  protected MimeMessage formatThermostateOffMessage(
      String templateID, ThermostatDTO status, String... recipients) {

    MimeMessage message = null;

    Configuration cfg = new Configuration();

    try {

      InputStream tis = this.getClass().getResourceAsStream(templateID);

      Template template = new Template(templateID, new InputStreamReader(tis), cfg);

      Map<String, Object> model = new HashMap<String, Object>();

      model.put("status", status);
      model.put(
          "sx", (status.getTargetTemperature() > status.getCurrentTemperature()) ? "aan" : "af");

      StringWriter bodyWriter = new StringWriter();

      template.process(model, bodyWriter);

      bodyWriter.flush();

      message = this.javaMailSender.createMimeMessage();
      // SGL| GAE does not support multipart_mode_mixed_related (default, when flag true is set)
      MimeMessageHelper helper =
          new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_NO, "utf-8");

      helper.setFrom("*****@*****.**");
      helper.setTo(recipients);
      helper.setSubject("Casa Zoncolan verwarmingsrapport");

      String text = bodyWriter.toString();

      logger.info("email text is [{}]", text);

      helper.setText(text, true);

    } catch (Exception e) {
      logger.warn("could not create e-mail", e);
      throw new RuntimeException(e);
    }

    return message;
  }
Ejemplo n.º 27
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);
  }
Ejemplo n.º 28
0
  /*
   * (non-Javadoc)
   *
   * @see ims.mary.service.mail.MailService#sendTemplateMail(java.lang.String,
   * java.lang.String, java.lang.String, java.lang.String, java.util.Map)
   */
  public boolean sendTemplateMail(
      String[] to, String from, String subject, String tpl, Map<String, Object> params)
      throws ServiceException {

    //			String htmlText = getHtmlTextFromTemplate(tpl, params);
    //
    //			MimeMessage msg = mailSender.createMimeMessage();
    //			MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
    //			helper.setFrom(from);
    //			helper.setTo(to);
    //			helper.setSubject(subject);
    //			helper.setText(htmlText, true);
    //
    //			mailSender.send(msg);

    for (String tmp : to) {
      MimeMessage msg;
      try {
        String htmlText = getHtmlTextFromTemplate(tpl, params);
        msg = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
        helper.setFrom(from);
        String[] list = new String[1];
        list[0] = tmp;
        helper.setTo(list);
        helper.setSubject(subject);
        helper.setText(htmlText, true);
      } catch (Exception e) {
        // Do Nothing
        logger.error("send mail failed," + e);
        return false;
        // throw new ServiceException(e);
      }
      try {
        mailSender.send(msg);
      } catch (Exception e) {
        // Do Nothing
        logger.error("send mail failed," + e);
      }
    }

    return true;
  }
  @Override
  public void sendMail(String fromUser, String toUser, String subject, String text) {

    MimeMessage message = mailSender.createMimeMessage();

    try {
      MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");

      messageHelper.setFrom(fromUser);
      messageHelper.setTo(toUser);
      messageHelper.setSubject(subject);
      messageHelper.setText(text, true);

      mailSender.send(message);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 30
0
 @Override
 @Async
 public void nieuwFiliaalMail(Filiaal filiaal, String urlFiliaal) {
   try {
     MimeMessage message = sender.createMimeMessage();
     MimeMessageHelper helper = new MimeMessageHelper(message);
     helper.setTo(webmaster);
     helper.setSubject("Nieuw filiaal");
     helper.setText(
         String.format(
             "Je kan het nieuwe filiaal <strong>%s</strong> "
                 + "<a href='%s/wijzigen'>hier</a> nazien",
             filiaal.getNaam(), urlFiliaal),
         true);
     sender.send(message);
   } catch (Exception ex) {
     logger.log(Level.SEVERE, "kan mail nieuw filiaal niet versturen", ex);
     throw new RuntimeException("Kan mail nieuw filiaal niet versturen", ex);
   }
 }