Exemple #1
0
  public static void sendSmtpMessage(Session session, Message message, Address[] recipients)
      throws MessagingException {

    // message = cloneMimeMessage(message);
    message.setSentDate(new Date());
    setHeaderFieldValue(message, HEADER_X_MAILER, X_MAILER);
    message.saveChanges();

    LOG.info(
        "Sending message '"
            + message.getSubject()
            + "' from '"
            + Str.format(message.getFrom())
            + "' to '"
            + Str.format(recipients)
            + "'.");

    Transport trans = session.getTransport("smtp");
    Properties properties = session.getProperties();
    trans.connect(
        properties.getProperty("mail.smtp.host"),
        properties.getProperty("mail.smtp.auth.user"),
        properties.getProperty("mail.smtp.auth.password"));
    trans.sendMessage(message, recipients);
    trans.close();
  }
 @Test
 public void savedWithoutError() throws Exception {
   Session session = Session.getDefaultInstance(new Properties());
   // Instantiate a Multipart object
   MimeMultipart mp = new MimeMultipart();
   // create the first bodypart object
   MimeBodyPart b1 = new MimeBodyPart();
   // create textual content
   // and add it to the bodypart object
   b1.setContent("Spaceport Map", "text/plain");
   mp.addBodyPart(b1);
   // Multipart messages usually have more than
   // one body part. Create a second body part
   // object, add new text to it, and place it
   // into the multipart message as well. This
   // second object holds postscript data.
   MimeBodyPart b2 = new MimeBodyPart();
   b2.setDataHandler(new DataHandler(new FileDataSource("project.xml")));
   mp.addBodyPart(b2);
   // Create a new message object as described above,
   // and set its attributes. Add the multipart
   // object to this message and call saveChanges()
   // to write other message headers automatically.
   Message msg = new MimeMessage(session);
   // Set message attrubutes as in a singlepart
   // message.
   msg.setContent(mp); // add Multipart
   msg.saveChanges(); // save changes
 }
  public void sendMail(String from, String to, String subject, String message) {

    Properties props = new Properties();

    // para SERVIDOR PROXY descomente essa parte e atribua as propriedades
    /*
                 props.setProperty("proxySet","true");
                 props.setProperty("socksProxyHost","192.168.155.1"); // IP do Servidor Proxy
                 props.setProperty("socksProxyPort","1080");  // Porta do servidor Proxy
    */

    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", mailSMTPServer);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.user", from);
    props.put("mail.debug", "false");
    props.put("mail.smtp.port", mailSMTPServerPort); // porta
    props.put("mail.smtp.socketFactory.port", mailSMTPServerPort); // mesma porta para o socket
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SimpleAuth auth = null;
    auth = new SimpleAuth("*****@*****.**", "****");

    Session session = Session.getDefaultInstance(props, auth);
    //		session.setDebug(true); //Habilita o LOG das ações executadas durante o envio do email

    Message msg = new MimeMessage(session);

    try {
      msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
      msg.setFrom(new InternetAddress(from));
      msg.setSubject(subject);
      message += "\n\n Enviado por: " + from;
      msg.setContent(message, "text/plain");
    } catch (Exception e) {
      System.out.println(">> Erro: Completar Mensagem");
      e.printStackTrace();
    }

    Transport tr;
    try {
      tr = session.getTransport("smtp"); // define smtp para transporte
      tr.connect(mailSMTPServer, "*****@*****.**", "***");
      msg.saveChanges(); // don't forget this
      // envio da mensagem
      tr.sendMessage(msg, msg.getAllRecipients());
      tr.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #4
0
  public void sendMail2(
      String mimeType,
      String from,
      String to,
      String subject,
      String text,
      MimeBodyPart... attachments) {
    if (Utils.isNullOrEmpty(to)) {
      logger.warn("mail can't be delivered to (recipient == null):\n{}", text);
      return;
    }

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

    Message message = new MimeMessage(session);

    try {
      Multipart mp = new MimeMultipart("mixed");

      BodyPart content = new MimeBodyPart();
      content.setContent(text, mimeType);
      mp.addBodyPart(content);

      if (attachments != null && attachments.length > 0) {
        for (MimeBodyPart attachment : attachments) {
          mp.addBodyPart(attachment);
        }
      }

      message.setFrom(
          new InternetAddress(
              from, from.equals(PING_SERVICE_NOTIFY_GMAIL_COM) ? "Ping Service Notifier" : null));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject(subject);
      message.setContent(mp);
      message.saveChanges();

      Transport.send(message);
    } catch (Exception e) {
      logger.error(
          "Error sending mail:"
              + "\n\tFrom: "
              + from
              + "\n\tTo: "
              + to
              + "\n\tSubject: "
              + subject
              + "\n\tMessage:\n\n"
              + (Utils.isNullOrEmpty(text) ? "-" : text.substring(0, 100) + "..."),
          e);
    }
  }
Exemple #5
0
  public static int sendMail(String toAddr, String ccAddr, String mailTitle, String mailConcept) {
    Session s = Session.getInstance(SendMail.props, null);
    s.setDebug(false);

    Message message = new MimeMessage(s);
    try {
      Address from = new InternetAddress(SendMail.SenderEmailAddr);
      message.setFrom(from);
      Address to = new InternetAddress(toAddr);
      message.setRecipient(Message.RecipientType.TO, to);
      if (ccAddr != null && ccAddr != "") {
        Address cc = new InternetAddress(ccAddr);
        message.setRecipient(Message.RecipientType.CC, cc);
      }

      message.setSubject(mailTitle);
      Multipart mainPart = new MimeMultipart();
      BodyPart html = new MimeBodyPart();
      html.setContent(mailConcept, "text/html;charset=ISO-8859-1");
      mainPart.addBodyPart(html);
      message.setContent(mainPart);
      message.setSentDate(new Date());
      message.saveChanges();

      Transport transport = s.getTransport(SendMail.TransprotType);
      transport.connect(SendMail.SMTPServerName, SendMail.SMTPUserName, SendMail.SMTPPassword);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();

      //			System.out.println("发送邮件,邮件地址:"+toAddr);
      //			System.out.println("发送邮件,邮件地址:"+ccAddr);
      //			System.out.println("标题:"+mailTitle);
      //			System.out.println("内容:"+mailConcept);
      System.out.println("Email Send Success!");
      return 1;
    } catch (Exception e) {
      System.out.println(e.getMessage());
      return -1;
    }
  }
Exemple #6
0
  private boolean enviarSMTP(Message mensagem) {
    boolean ok = true;
    try {
      if (!_servidorSMTPRequerLogin) {
        Transport.send(mensagem);
      } else {
        Transport tr = _sessao.getTransport("smtp");
        tr.connect(
            _propriedades.getProperty(PROPRIEDADE_SMTP_HOST),
            _propriedades.getProperty(PROPRIEDADE_SMTP_USER),
            _propriedades.getProperty(PROPRIEDADE_STMP_PASSWORD));
        mensagem.saveChanges();
        tr.sendMessage(mensagem, mensagem.getAllRecipients());
        tr.close();
      }
    } catch (MessagingException ex) {
      Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
      ok = false;
    }

    return ok;
  }
Exemple #7
0
  public void send(final String from, final String to, final String subject, final String content)
      throws AddressException, MessagingException {
    Session session = Session.getDefaultInstance(props, null);

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    String[] toAddresses = to.split(",");
    for (int i = 0; i < toAddresses.length; i++) {
      msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddresses[i]));
    }
    msg.setSubject(subject);
    msg.setText(content);

    if (auth) {
      Transport transport = session.getTransport("smtp");
      transport.connect(host, port, username, password);
      msg.saveChanges();
      transport.sendMessage(msg, msg.getAllRecipients());
      transport.close();
    } else {
      Transport.send(msg);
    }
  }
Exemple #8
0
  public static void send(
      String smtpServer, String to, String from, String psw, String subject, String body)
      throws Exception {
    // java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    Properties props = System.getProperties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.starttls.enable", "true");
    final String login = from; // ”[email protected]”;//usermail
    final String pwd = psw; // ”password cua ban o day”;
    Authenticator pa = null; // default: no authentication
    if (login != null && pwd != null) { // authentication required?
      props.put("mail.smtp.auth", "true");
      pa =
          new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication(login, pwd);
            }
          };
    } // else: no authentication
    Session session = Session.getInstance(props, pa);
    // — Create a new message –
    Message msg = new MimeMessage(session);
    // — Set the FROM and TO fields –
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

    // — Set the subject and body text –
    msg.setSubject(subject);
    msg.setText(body);
    // — Set some other header information –
    msg.setHeader("X-Mailer", "LOTONtechEmail");
    msg.setSentDate(new Date());
    msg.saveChanges();
    // — Send the message –
    Transport.send(msg);
  }
Exemple #9
0
  /**
   * Sends mail.
   *
   * @return
   */
  public int send() {
    int status = 0;
    String messageBody = null;
    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 {
      CyberoamLogger.sysLog.debug("Getting System Properties .....");
      props = System.getProperties();

      CyberoamLogger.sysLog.debug("Setting SMTP Mail Host and SMTP Mail Port  .....");
      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();
      }

      CyberoamLogger.sysLog.debug("Getting session for mail sending .....");
      // if auth is null then session without authentication will be created.
      session = Session.getInstance(props, auth);

      CyberoamLogger.sysLog.debug("Initializing mail contents .....");
      messageBody = mailContentFile;

      CyberoamLogger.sysLog.debug("Preparing a message body .....");
      message = new MimeMessage(session);
      message.setHeader("X-Mailer", "Cyberoam Mail Client");
      message.setHeader("Content-Type", "text/html; charset=UTF-8");

      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);
      message.setText(messageBody);
      message.setContent(messageBody, "text/html");
      message.saveChanges();
      CyberoamLogger.sysLog.debug("Message Content Type: " + message.getContentType());
      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();
      CyberoamLogger.sysLog.debug("Mail sent OK.");
      AuditLog.mail.info("Mail with subject :\"" + mailSubject + "\" sent to " + smtpToAddr, null);

    } 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;
  }
Exemple #10
0
  /**
   * 邮件发送
   *
   * @param mailInfo
   * @param isHtml
   * @return
   * @throws MessagingException
   * @throws UnsupportedEncodingException
   */
  private boolean send(MailSenderInfo mailInfo, boolean isHtml) throws MessagingException {
    // 判断是否需要身份认证
    SMTPAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
      // 如果需要身份认证,则创建一个密码验证器
      authenticator = new SMTPAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
    // 根据session创建一个邮件消息
    Message mailMessage = new MimeMessage(sendMailSession);
    // 创建邮件发送者地址
    Address from = null;
    try {
      from = new InternetAddress(mailInfo.getFromAddress(), mailInfo.getFromName());
    } catch (UnsupportedEncodingException e) {
      from = new InternetAddress(mailInfo.getFromAddress());
    }
    // 设置邮件消息的发送者
    mailMessage.setFrom(from);
    // 创建邮件的接收者地址,并设置到邮件消息中
    Address[] to = new InternetAddress[mailInfo.getToAddress().size()];
    int i = 0;
    for (String temp : mailInfo.getToAddress()) {
      to[i++] = new InternetAddress(temp);
    }
    mailMessage.setRecipients(Message.RecipientType.TO, to);
    // 设置邮件消息的主题
    mailMessage.setSubject(mailInfo.getSubject());
    // 设置邮件消息发送的时间
    mailMessage.setSentDate(new Date());

    // 邮件对象,MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
    Multipart mainPart = new MimeMultipart();

    // 邮件正文
    BodyPart mailBody = new MimeBodyPart();
    if (isHtml) {
      // 设置HTML内容
      mailBody.setContent(mailInfo.getContent(), "text/html; charset=" + mailInfo.getCharset());
    } else {
      // 设置非HTML内容
      mailBody.setText(mailInfo.getContent());
    }
    mainPart.addBodyPart(mailBody); // 添加邮件正文至邮件对象

    // 邮件附件
    for (MailAttachment item : mailInfo.getAttachFiles()) {
      BodyPart attachment = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(item.getAbsoluteFile()); // 得到附件数据源
      attachment.setDataHandler(new DataHandler(fds)); // 得到附件本身
      // 设置文件名,并解决中文名乱码问题
      String fileName = item.getAliasName();
      try {
        attachment.setFileName(MimeUtility.encodeText(fileName));
      } catch (UnsupportedEncodingException e) {
        attachment.setFileName(fileName);
      }
      mainPart.addBodyPart(attachment); // 添加邮件附件至邮件对象
    }

    // 添加邮件内容对象
    mailMessage.setContent(mainPart);
    // 保存邮件
    mailMessage.saveChanges();
    // 发送邮件
    Transport.send(mailMessage);
    return true;
  }