Example #1
0
  public void setMessageContent(
      MimeMessage message, String subject, String bodyText, String bodyHtml) {
    try {
      message.setSubject(subject);

      MimeBodyPart textPart = new MimeBodyPart();
      textPart.setText(bodyText.toString(), "UTF-8");

      MimeBodyPart htmlPart = new MimeBodyPart();
      htmlPart.setContent(bodyHtml.toString(), "text/html; charset=UTF-8");

      MimeMultipart multiPart = new MimeMultipart();
      // "alternative" means display only one or the other, "mixed" means both
      multiPart.setSubType("alternative");

      // I read something on the internet saying to put the text part first
      // so sucktastic mail clients see it first
      multiPart.addBodyPart(textPart);
      multiPart.addBodyPart(htmlPart);

      message.setContent(multiPart);
    } catch (MessagingException e) {
      throw new RuntimeException("failed to put together MIME message", e);
    }
  }
Example #2
0
 @Override
 public synchronized void setSubType(String subtype) throws MessagingException {
   if (ZPARSER) {
     zmultipart.setContentType(zmultipart.getContentType().setSubType(subtype));
   } else {
     super.setSubType(subtype);
   }
 }
Example #3
0
  private Message createMessage(Session session, User user2) throws Exception {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(email));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
    message.setSubject("中工精品课程修改密码邮件");

    // 创建MimeBodyPart封装正文
    MimeBodyPart text = new MimeBodyPart();

    Date time = new Date();

    String con =
        "尊敬的"
            + user.getNickname()
            + "您好!</br>下面是重置密码的链接,<font color='red'>一个小时之内请点击进入重置密码,否则失效</font>,我会等着你的哦!"
            + "<div><a href='http://localhost:8080/ExcellentCourse/servlet/ResetPwdServlet?uid="
            + user.getId()
            + "&time="
            + time.getTime()
            + "'>重置密码   uid="
            + user.getId()
            + "  time="
            + time.getTime()
            + " </a></div>"
            + "<img src='cid:logo'/>";
    text.setContent(con, "text/html;charset=UTF-8");

    // chuangjian image
    // 创建图片
    MimeMultipart mm = new MimeMultipart();

    BodyPart image1 = createInlineImagePart(context.getRealPath("images/email/beauty.jpg"));
    image1.setHeader("Content-ID", "logo");
    mm.addBodyPart(text);
    mm.addBodyPart(image1);
    mm.setSubType("related");

    message.setContent(mm);
    message.saveChanges();
    // message.writeTo(new FileOutputStream("c:\\1.eml"));
    return message;
  }
Example #4
0
    @Override
    public MimeMessage build(Session session)
        throws MessagingException, UnsupportedEncodingException {
      MimeMessage message = super.build(session);

      if (fromName == null) {
        message.setFrom(new InternetAddress(fromAddress));
      } else {
        message.setFrom(new InternetAddress(fromAddress, fromName));
      }
      message.setSubject(subject, "utf-8");

      for (String email : recipients) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
      }

      if (replyTos.size() > 0) {
        message.setReplyTo(replyTos.toArray(new InternetAddress[replyTos.size()]));
      }

      MimeMultipart multipart = new MimeMultipart();
      if (plainTextPart != null) {
        // we are sending a plain-text alternative in addition
        multipart.addBodyPart(plainTextPart);
        multipart.setSubType("alternative");
      }
      multipart.addBodyPart(messageBodyPart);

      for (BodyPart bodyPart : bodyParts) {
        multipart.addBodyPart(bodyPart);
      }

      message.setContent(multipart);

      return message;
    }
Example #5
0
  @Override
  public void send(MailMessage message) {
    if (StringUtils.isEmpty(host)) {
      String errorText = "SMTP Host can't be null!";
      logger.error(errorText);
      throw new IllegalArgumentException(errorText);
    }

    if (message == null) {
      String errorText = "EmailMessage can't be null!";
      logger.error(errorText);
      throw new IllegalArgumentException(errorText);
    }

    Session session;

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    if (useTls) {
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.port", tlsPort);

      // Note - not really tested.
    } else if (useSsl) {
      props.put("mail.smtp.socketFactory.port", sslPort);
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.port", sslPort);
    }

    if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
      props.put("mail.smtp.auth", "true");
      session =
          Session.getInstance(
              props,
              new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(username, password);
                }
              });

    } else {
      session = Session.getInstance(props);
    }

    try {
      Message mimeMessage = new MimeMessage(session);

      mimeMessage.setFrom(new InternetAddress(message.getFrom()));
      mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(message.getTo()));
      mimeMessage.setSubject(message.getSubject());

      if (!StringUtils.isEmpty(message.getReplyTo())) {
        mimeMessage.setReplyTo(InternetAddress.parse(message.getReplyTo()));
      }

      // Body, plain vs. html
      MimeMultipart multiPartContent = new MimeMultipart();

      if (!StringUtils.isEmpty(message.getBodyPlain())) {
        MimeBodyPart plain = new MimeBodyPart();
        plain.setText(message.getBodyPlain());
        multiPartContent.addBodyPart(plain);
      }

      if (!StringUtils.isEmpty(message.getBodyHtml())) {
        MimeBodyPart html = new MimeBodyPart();
        html.setContent(message.getBodyHtml(), "text/html");
        multiPartContent.addBodyPart(html);
        multiPartContent.setSubType("alternative");
      }

      mimeMessage.setContent(multiPartContent);

      Transport.send(mimeMessage);
      logger.info("Sent email to [{}] with subject [{}].", message.getTo(), message.getSubject());

    } catch (MessagingException me) {
      logger.warn("Failed to send: [{}]", me.getMessage());
      me.printStackTrace();
      throw new RuntimeException(me);
    }
  }
Example #6
0
 /** Description of the Method */
 public boolean sendMessage() {
   MimeMultipart mp = new MimeMultipart();
   try {
     // if there is a text and an html section
     if (sendingText.getCount() > 1) {
       sendingText.setSubType("alternative");
     }
     // if we are sending attachments
     if (sendingAttachments.getCount() > 0) {
       MimeBodyPart bp = new MimeBodyPart();
       bp.setContent(sendingAttachments);
       mp.addBodyPart(bp, 0);
       bp = new MimeBodyPart();
       bp.setContent(sendingText);
       mp.addBodyPart(bp, 0);
     } else {
       mp = sendingText;
     }
     Logger.debug(this, "Getting the MailContext.");
     /*
      *
      * Get the mail session from
      *
      * the container Context
      */
     Session session = null;
     Context ctx = null;
     try {
       ctx = (Context) new InitialContext().lookup("java:comp/env");
       session = (javax.mail.Session) ctx.lookup("mail/MailSession");
     } catch (Exception e1) {
       try {
         Logger.debug(this, "Using the jndi intitialContext().");
         ctx = new InitialContext();
         session = (javax.mail.Session) ctx.lookup("mail/MailSession");
       } catch (Exception e) {
         Logger.error(this, "Exception occured finding a mailSession in JNDI context.");
         Logger.error(this, e1.getMessage(), e1);
         return false;
       }
     }
     if (session == null) {
       Logger.debug(this, "No Mail Session Available.");
       return false;
     }
     Logger.debug(
         this, "Delivering mail using: " + session.getProperty("mail.smtp.host") + " as server.");
     MimeMessage message = new MimeMessage(session);
     message.addHeader("X-RecipientId", String.valueOf(getRecipientId()));
     if ((fromEmail != null) && (fromName != null) && (0 < fromEmail.trim().length())) {
       message.setFrom(new InternetAddress(fromEmail, fromName));
     } else if ((fromEmail != null) && (0 < fromEmail.trim().length())) {
       message.setFrom(new InternetAddress(fromEmail));
     }
     if (toName != null) {
       String[] recipients = toEmail.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient, toName));
       }
     } else {
       String[] recipients = toEmail.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
       }
     }
     if (UtilMethods.isSet(cc)) {
       String[] recipients = cc.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.CC, new InternetAddress(recipient));
       }
     }
     if (UtilMethods.isSet(bcc)) {
       String[] recipients = bcc.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.BCC, new InternetAddress(recipient));
       }
     }
     message.setSubject(subject, encoding);
     message.setContent(mp);
     Transport.send(message);
     result = "Send Ok";
     return true;
   } catch (javax.mail.SendFailedException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("javax.mail.SendFailedException:")
                 + "javax.mail.SendFailedException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   } catch (MessagingException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("javax.mail.MessagingException:")
                 + "javax.mail.MessagingException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   } catch (UnsupportedEncodingException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("java.io.UnsupportedEncodingException:")
                 + "java.io.UnsupportedEncodingException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   }
 }