コード例 #1
0
ファイル: EMailUtils.java プロジェクト: zengyh/CodeLibary
  /**
   * 构建邮件
   *
   * @param session
   * @param uid 邮箱账号,如[email protected]
   * @param receivers 收件人地址,如new String[]{[email protected]}
   * @param subject 主题
   * @param content 邮件文本内容
   * @param vector 附件,如 new Vector(){ add("D:/uploadDir/test.txt"); }
   * @return
   * @throws javax.mail.internet.AddressException
   * @throws javax.mail.MessagingException
   * @throws java.io.UnsupportedEncodingException
   */
  public static Message buildMimeMessage(
      Session session,
      String uid,
      String[] receivers,
      String subject,
      String content,
      Vector<String> vector)
      throws AddressException, MessagingException, UnsupportedEncodingException {

    Message msg = new MimeMessage(session);

    msg.addFrom(InternetAddress.parse(uid)); // 发件人地址
    msg.setReplyTo(InternetAddress.parse(uid)); // 回复时用的地址
    // 消息接收者
    Address address[] = new Address[receivers.length];
    for (int i = 0; i < receivers.length; i++) {
      address[i] = new InternetAddress(receivers[i]);
    }
    msg.addRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setSentDate(new Date());

    // 邮件内容数据(Content)
    msg.setContent(buildMimeMultipart(content, vector));

    return msg;
  }
コード例 #2
0
ファイル: Eml.java プロジェクト: evanleonard/ilarkesto
 public static void setReplyTo(Message msg, String email) {
   try {
     msg.setReplyTo(new Address[] {new InternetAddress(email)});
   } catch (AddressException ex) {
     throw new RuntimeException(ex);
   } catch (MessagingException ex) {
     throw new RuntimeException(ex);
   }
 }
コード例 #3
0
  @Override
  public void execute(Activity activity) {
    log.info("Executing SendEmail Command.");
    modelSingleton = ModelSingleton.getInstance();
    SendEmail send = (SendEmail) activity;

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(send.getFrom(), send.getNickname()));
      if (send.getResponse().length() > 0)
        msg.setReplyTo(new Address[] {new InternetAddress(send.getResponse())});

      // Recipient entered manually
      if (!send.getTo().startsWith("$"))
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(send.getTo(), send.getTo()));
      // Linked to a Variable
      else {
        msg.addRecipient(
            Message.RecipientType.TO,
            new InternetAddress(
                (String)
                    modelSingleton
                        .variables
                        .get(NameUtil.normalizeVariableName(send.getTo()))
                        .getValue()));
      }

      msg.setSubject(send.getSubject());

      // Message Text entered manually
      if (!send.getBody().getValue().startsWith("$")) msg.setText(send.getBody().getValue());
      // Linked to a Variable
      else {
        msg.setText(
            (String)
                modelSingleton
                    .variables
                    .get(NameUtil.normalizeVariableName(send.getBody().getValue()))
                    .getValue());
      }
      Transport.send(msg);

    } catch (AddressException e) {
      log.info(e.getMessage());
    } catch (MessagingException e) {
      log.info(e.getMessage());
    } catch (UnsupportedEncodingException e) {
      log.info(e.getMessage());
    }
  }
コード例 #4
0
ファイル: JavaMailMailer.java プロジェクト: ksen938/thundr
  @Override
  protected void sendInternal(
      Map.Entry<String, String> from,
      Map.Entry<String, String> replyTo,
      Map<String, String> to,
      Map<String, String> cc,
      Map<String, String> bcc,
      String subject,
      Object body,
      List<Attachment> attachments) {
    try {
      Session emailSession = getSession();

      Message message = new MimeMessage(emailSession);
      message.setFrom(emailAddress(from));
      if (replyTo != null) {
        message.setReplyTo(new Address[] {emailAddress(replyTo)});
      }

      message.setSubject(subject);

      BasicViewRenderer viewRenderer = render(body);
      String content = viewRenderer.getOutputAsString();
      String contentType = ContentType.cleanContentType(viewRenderer.getContentType());
      contentType = StringUtils.isBlank(contentType) ? ContentType.TextHtml.value() : contentType;

      if (Expressive.isEmpty(attachments)) {
        message.setContent(content, contentType);
      } else {
        Multipart multipart =
            new MimeMultipart(
                "mixed"); // subtype must be "mixed" or inline & regular attachments won't play well
        // together
        addBody(multipart, content, contentType);
        addAttachments(multipart, attachments);
        message.setContent(multipart);
      }

      addRecipients(to, message, RecipientType.TO);
      addRecipients(cc, message, RecipientType.CC);
      addRecipients(bcc, message, RecipientType.BCC);

      sendMessage(message);
    } catch (MessagingException e) {
      throw new MailException(e, "Failed to send an email: %s", e.getMessage());
    }
  }
コード例 #5
0
  private void doit(String[] argv) {
    String to = null,
        subject = null,
        from = null,
        replyTo = null,
        cc = null,
        bcc = null,
        url = null;
    String mailhost = null;
    String mailer = "MsgSend";
    String protocol = null, host = null, user = null, password = null, record = null;
    String filename = null, msg_text = null, inline_filename = null;
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
      if (argv[optind].equals("-T")) {
        protocol = argv[++optind];
      } else if (argv[optind].equals("-X")) {
        msg_text = argv[++optind];
      } else if (argv[optind].equals("-H")) {
        host = argv[++optind];
      } else if (argv[optind].equals("-U")) {
        user = argv[++optind];
      } else if (argv[optind].equals("-P")) {
        password = argv[++optind];
      } else if (argv[optind].equals("-M")) {
        mailhost = argv[++optind];
      } else if (argv[optind].equals("-f")) {
        filename = argv[++optind];
      } else if (argv[optind].equals("-i")) {
        inline_filename = argv[++optind];
      } else if (argv[optind].equals("-s")) {
        subject = argv[++optind];
      } else if (argv[optind].equals("-o")) { // originator (from)
        from = argv[++optind];
      } else if (argv[optind].equals("-r")) { // reply-to
        replyTo = argv[++optind];
      } else if (argv[optind].equals("-c")) {
        cc = argv[++optind];
      } else if (argv[optind].equals("-b")) {
        bcc = argv[++optind];
      } else if (argv[optind].equals("-L")) {
        url = argv[++optind];
      } else if (argv[optind].equals("-d")) {
        debug = true;
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        System.err.println(USAGE_TEXT);
        System.exit(1);
      } else {
        break;
      }
    }

    try {
      if (optind < argv.length) {
        // XXX - concatenate all remaining arguments
        to = argv[optind];
        System.out.println("To: " + to);
      } else {
        System.out.print("To: ");
        System.out.flush();
        to = in.readLine();
      }
      if (subject == null) {
        System.out.print("Subject: ");
        System.out.flush();
        subject = in.readLine();
      } else {
        System.out.println("Subject: " + subject);
      }

      Properties props = System.getProperties();
      // XXX - could use Session.getTransport() and Transport.connect()
      // XXX - assume we're using SMTP
      if (mailhost != null) props.put("mail.smtp.host", mailhost);

      // Get a Session object
      Session session = Session.getInstance(props, null);
      if (debug) session.setDebug(true);

      // construct the message
      Message msg = new MimeMessage(session);

      if (from != null) msg.setFrom(new InternetAddress(from));
      else msg.setFrom();

      if (reply_to_list == null && replyTo != null) {
        reply_to_list = new InternetAddress[1];
        reply_to_list[0] = new InternetAddress(replyTo);
        msg.setReplyTo(reply_to_list);
      } else msg.setReplyTo(reply_to_list);

      if (dis_list == null) {
        dis_list = new InternetAddress[1];
        dis_list[0] = new InternetAddress(to);
      }

      msg.setRecipients(Message.RecipientType.TO, dis_list);
      if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
      if (bcc != null)
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

      // in-line file contents if specified
      if (inline_filename != null) {
        msg_text = readFile(inline_filename);
      }

      // create and fill the first message part
      MimeBodyPart mbp1 = new MimeBodyPart();
      mbp1.setText(msg_text);

      // create the Multipart and add the text part
      Multipart mp = new MimeMultipart();
      mp.addBodyPart(mbp1);

      // create additional message part(s)

      // attach the file or files to the message
      if (filename != null) {
        MimeBodyPart mbp = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(filename);
        mbp.setDataHandler(new DataHandler(fds));
        mbp.setFileName(fds.getName());
        mp.addBodyPart(mbp);
        mbp1.setText(msg_text + "\n\nAttachment: " + filename);
        System.out.println("Added attachment: " + filename);
      }

      if (attachments != null) {
        Iterator i = attachments.iterator();
        StringBuffer list = null;
        while (i.hasNext()) {
          String name = (String) i.next();
          MimeBodyPart mbp = new MimeBodyPart();
          FileDataSource fds = new FileDataSource(name);
          mbp.setDataHandler(new DataHandler(fds));
          mbp.setFileName(fds.getName());
          mp.addBodyPart(mbp);
          if (list == null) {
            list = new StringBuffer(name);
          } else {
            list.append(", " + name);
          }
          System.out.println("Added attachment: " + name);
          mbp1.setText(msg_text + "\nAttachment(s): " + list);
        }
      }

      // add the Multipart to the message
      msg.setContent(mp);

      msg.setSubject(subject);

      // jgfrun collect(in, msg);

      msg.setHeader("X-Mailer", mailer);
      msg.setSentDate(new Date());

      // send the thing off
      Transport.send(msg);

      System.out.println("Mail was sent successfully.");

      // Keep a copy, if requested.
      if (record != null) {

        // Get a Store object
        Store store = null;
        if (url != null) {
          URLName urln = new URLName(url);
          store = session.getStore(urln);
          store.connect();
        } else {
          if (protocol != null) store = session.getStore(protocol);
          else store = session.getStore();

          // Connect
          if (host != null || user != null || password != null) store.connect(host, user, password);
          else store.connect();
        }

        // Get record Folder. Create if it does not exist.
        Folder folder = store.getFolder(record);
        if (folder == null) {
          System.err.println("Can't get record folder.");
          System.exit(1);
        }
        if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES);

        Message[] msgs = new Message[1];
        msgs[0] = msg;
        folder.appendMessages(msgs);

        System.out.println("Mail was recorded successfully.");
      }

    } catch (Exception e) {
      System.err.println("Could not MsgSend.doit");
      e.printStackTrace();
    }
  } // doit
コード例 #6
0
ファイル: SmtpMailProvider.java プロジェクト: jamesvivid/dari
  @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);
    }
  }
コード例 #7
0
ファイル: MailSender.java プロジェクト: xujun10110/iView
  /**
   * Sends mail with attachment.
   *
   * @param mimeAttachment
   * @return
   */
  public int sendWithAttachment(MimeBodyPart mimeAttachment) {
    int status = 0;
    Properties props = null;
    Session session = null;
    Message message = null;
    Authenticator auth = null;
    Transport transport = null;
    if (smtpServerHost == null || "".equalsIgnoreCase(smtpServerHost)) {
      CyberoamLogger.sysLog.debug(
          "mail send is stopped because smtpserverhost in tbliviewconfig is not exist.");
      return -1;
    }
    try {
      props = System.getProperties();

      CyberoamLogger.sysLog.debug("Set MailServer configuration");
      props.put(MAILSMTPHOST, smtpServerHost);
      props.put(MAILSMTPPORT, smtpServerPort);
      props.put(MAILDEBUG, VALUEFALSE);
      props.put(MAILSMTPAUTH, VALUEFALSE);
      CyberoamLogger.sysLog.debug(
          "SMTP Mail Host :: SMTP Mail Port - " + smtpServerHost + " :: " + smtpServerPort);

      if ("1".equals(smtpAuthFlag)) {
        props.put(MAILSMTPAUTH, VALUETRUE);
        props.put(MAILSMTPUSER, smtpUsername);
        auth = new SMTPAuthenticator();
      }

      session = Session.getInstance(props, auth);
      message = new MimeMessage(session);
      message.setHeader("X-Mailer", "iView Mail Client");
      if (smtpDisplayName == null || "".equalsIgnoreCase(smtpDisplayName))
        message.setFrom(new InternetAddress(smtpFromAddr));
      else message.setFrom(new InternetAddress(smtpFromAddr, smtpDisplayName));
      CyberoamLogger.sysLog.debug("Mail will be sent to: " + smtpToAddr);
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpToAddr, false));
      InternetAddress replyAddress[] = new InternetAddress[1];
      replyAddress[0] = new InternetAddress("*****@*****.**");
      message.setReplyTo(replyAddress);

      message.setSentDate(new Date());
      message.setSubject(mailSubject);

      // create and fill the first message part
      MimeBodyPart textPart = new MimeBodyPart();
      textPart.setText(mailContentFile);
      textPart.setHeader("Content-Type", "text/html; charset=UTF-8");

      // create the Multipart and its parts to it
      Multipart mp = new MimeMultipart();
      mp.addBodyPart(mimeAttachment);

      mp.addBodyPart(textPart);
      // add the Multipart to the message
      message.setContent(mp);

      CyberoamLogger.sysLog.debug("Mail is ready to send .....");

      CyberoamLogger.sysLog.debug("Getting SMTP Transport Object for mail sending .....");
      transport = session.getTransport("smtp");

      if ("1".equals(smtpAuthFlag)) {
        CyberoamLogger.sysLog.debug("Connecting to SMTP MailServer Host with Authentication .....");
        transport.connect(smtpServerHost, smtpUsername, smtpPassword);
        CyberoamLogger.sysLog.debug("Sending Mail .....");
        transport.sendMessage(message, message.getAllRecipients());
      } else {
        CyberoamLogger.sysLog.debug(
            "Connecting to SMTP MailServer Host without Authentication .....");
        transport.connect();
        CyberoamLogger.sysLog.debug("Sending Mail .....");
        transport.sendMessage(message, message.getAllRecipients());
      }
      transport.close();
      AuditLog.mail.info("Mail with subject :\"" + mailSubject + "\" sent to " + smtpToAddr, null);
      CyberoamLogger.sysLog.debug("Mail sent OK.");
    } catch (MessagingException mex) {
      status = -1;
      AuditLog.mail.error("Mail sending failed : " + mex.getMessage(), null);
      CyberoamLogger.sysLog.debug("MailSender.sendWithAttachment.messageexception:" + mex, mex);
    } catch (Exception e) {
      status = -1;
      AuditLog.mail.error("Mail sending failed : " + e.getMessage(), null);
      CyberoamLogger.sysLog.debug("MailSender.sendWithAttachment.exception:" + e, e);
    }
    return status;
  }
コード例 #8
0
  /*
   * (non-Javadoc)
   *
   * @see org.mule.transformers.AbstractTransformer#doTransform(java.lang.Object)
   */
  public Object transform(Object src, UMOEventContext context) throws TransformerException {
    String endpointAddress = endpoint.getEndpointURI().getAddress();
    SmtpConnector connector = (SmtpConnector) endpoint.getConnector();
    String to = context.getStringProperty(MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress);
    String cc =
        context.getStringProperty(MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses());
    String bcc =
        context.getStringProperty(
            MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses());
    String from =
        context.getStringProperty(MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress());
    String replyTo =
        context.getStringProperty(
            MailProperties.REPLY_TO_ADDRESSES_PROPERTY, connector.getReplyToAddresses());
    String subject =
        context.getStringProperty(MailProperties.SUBJECT_PROPERTY, connector.getSubject());

    String contentType =
        context.getStringProperty(MailProperties.CONTENT_TYPE_PROPERTY, connector.getContentType());

    Properties headers = new Properties();
    if (connector.getCustomHeaders() != null) headers.putAll(connector.getCustomHeaders());
    Properties otherHeaders =
        (Properties) context.getProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY);
    if (otherHeaders != null) {
      Map props = new HashMap(MuleManager.getInstance().getProperties());
      props.putAll(context.getProperties());
      headers.putAll(templateParser.parse(props, otherHeaders));
    }

    if (logger.isDebugEnabled()) {
      StringBuffer buf = new StringBuffer();
      buf.append("Constucting email using:\n");
      buf.append("To: ").append(to);
      buf.append("From: ").append(from);
      buf.append("CC: ").append(cc);
      buf.append("BCC: ").append(bcc);
      buf.append("Subject: ").append(subject);
      buf.append("ReplyTo: ").append(replyTo);
      buf.append("Content type: ").append(contentType);
      buf.append("Payload type: ").append(src.getClass().getName());
      buf.append("Custom Headers: ").append(PropertiesHelper.propertiesToString(headers, false));
      logger.debug(buf.toString());
    }

    try {
      Message msg =
          new MimeMessage(
              (Session)
                  endpoint.getConnector().getDispatcher(endpointAddress).getDelegateSession());

      msg.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to));

      // sent date
      msg.setSentDate(Calendar.getInstance().getTime());

      if (from != null && !Utility.EMPTY_STRING.equals(from)) {
        msg.setFrom(MailUtils.stringToInternetAddresses(from)[0]);
      }

      if (cc != null && !Utility.EMPTY_STRING.equals(cc)) {
        msg.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc));
      }

      if (bcc != null && !Utility.EMPTY_STRING.equals(bcc)) {
        msg.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc));
      }

      if (replyTo != null && !Utility.EMPTY_STRING.equals(replyTo)) {
        msg.setReplyTo(MailUtils.stringToInternetAddresses(replyTo));
      }

      msg.setSubject(subject);

      Map.Entry entry;
      for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext(); ) {
        entry = (Map.Entry) iterator.next();
        msg.setHeader(entry.getKey().toString(), entry.getValue().toString());
      }

      setContent(src, msg, contentType, context);

      return msg;
    } catch (Exception e) {
      throw new TransformerException(this, e);
    }
  }
コード例 #9
0
  /*
   * (non-Javadoc)
   *
   * @see org.mule.transformers.AbstractEventAwareTransformer#transform(java.lang.Object,
   *      java.lang.String, org.mule.umo.UMOEventContext)
   */
  public Object transform(Object src, String encoding, UMOEventContext context)
      throws TransformerException {

    String endpointAddress = endpoint.getEndpointURI().getAddress();
    SmtpConnector connector = (SmtpConnector) endpoint.getConnector();
    UMOMessage eventMsg = context.getMessage();

    String to = eventMsg.getStringProperty(MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress);
    String cc =
        eventMsg.getStringProperty(
            MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses());
    String bcc =
        eventMsg.getStringProperty(
            MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses());
    String from =
        eventMsg.getStringProperty(
            MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress());
    String replyTo =
        eventMsg.getStringProperty(
            MailProperties.REPLY_TO_ADDRESSES_PROPERTY, connector.getReplyToAddresses());
    String subject =
        eventMsg.getStringProperty(MailProperties.SUBJECT_PROPERTY, connector.getSubject());
    String contentType =
        eventMsg.getStringProperty(
            MailProperties.CONTENT_TYPE_PROPERTY, connector.getContentType());

    Properties headers = new Properties();
    Properties customHeaders = connector.getCustomHeaders();

    if (customHeaders != null && !customHeaders.isEmpty()) {
      headers.putAll(customHeaders);
    }

    Properties otherHeaders =
        (Properties) eventMsg.getProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY);
    if (otherHeaders != null && !otherHeaders.isEmpty()) {
      Map props = new HashMap(MuleManager.getInstance().getProperties());
      for (Iterator iterator = eventMsg.getPropertyNames().iterator(); iterator.hasNext(); ) {
        String propertyKey = (String) iterator.next();
        props.put(propertyKey, eventMsg.getProperty(propertyKey));
      }
      headers.putAll(templateParser.parse(props, otherHeaders));
    }

    if (logger.isDebugEnabled()) {
      StringBuffer buf = new StringBuffer(256);
      buf.append("Constructing email using:\n");
      buf.append("To: ").append(to);
      buf.append("From: ").append(from);
      buf.append("CC: ").append(cc);
      buf.append("BCC: ").append(bcc);
      buf.append("Subject: ").append(subject);
      buf.append("ReplyTo: ").append(replyTo);
      buf.append("Content type: ").append(contentType);
      buf.append("Payload type: ").append(src.getClass().getName());
      buf.append("Custom Headers: ").append(PropertiesUtils.propertiesToString(headers, false));
      logger.debug(buf.toString());
    }

    try {
      Message email =
          new MimeMessage(
              (Session) endpoint.getConnector().getDispatcher(endpoint).getDelegateSession());

      // set mail details
      email.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to));
      email.setSentDate(Calendar.getInstance().getTime());
      if (StringUtils.isNotBlank(from)) {
        email.setFrom(MailUtils.stringToInternetAddresses(from)[0]);
      }
      if (StringUtils.isNotBlank(cc)) {
        email.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc));
      }
      if (StringUtils.isNotBlank(bcc)) {
        email.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc));
      }
      if (StringUtils.isNotBlank(replyTo)) {
        email.setReplyTo(MailUtils.stringToInternetAddresses(replyTo));
      }
      email.setSubject(subject);

      for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext(); ) {
        Map.Entry entry = (Map.Entry) iterator.next();
        email.setHeader(entry.getKey().toString(), entry.getValue().toString());
      }

      // Create Multipart to put BodyParts in
      Multipart multipart = new MimeMultipart();

      // Create Text Message
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText("My Text");
      multipart.addBodyPart(messageBodyPart);

      // Create Attachment
      messageBodyPart = new MimeBodyPart();
      DataHandler dataHandler = (DataHandler) src;
      messageBodyPart.setDataHandler(dataHandler);
      messageBodyPart.setFileName(dataHandler.getName());
      multipart.addBodyPart(messageBodyPart);

      email.setContent(multipart);

      return email;
    } catch (Exception e) {
      throw new TransformerException(this, e);
    }
  }