Beispiel #1
0
  private Message gerarMensagem(String emissor, String destino, String assunto) {
    Message mensagem = new MimeMessage(_sessao);
    try {
      mensagem.setFrom(new InternetAddress(emissor));
      mensagem.setRecipient(Message.RecipientType.TO, new InternetAddress(destino));
      mensagem.setSubject(assunto);

      if (_existemAnexos) {
        MimeBodyPart conteudo = new MimeBodyPart();
        if (_tipoMensagem.equals(Conteudo.HTML)) {
          conteudo.setContent(_texto, TipoConteudo.HTML);
        } else {
          conteudo.setContent(_texto, TipoConteudo.TEXTO);
        }
        Multipart divisoesConteudo = new MimeMultipart();
        divisoesConteudo.addBodyPart(conteudo);
        inserirAnexosArquivo(divisoesConteudo);
        inserirAnexosConteudo(divisoesConteudo);
        mensagem.setContent(divisoesConteudo);
      } else {
        if (_tipoMensagem.equals(Conteudo.HTML)) {
          mensagem.setContent(_texto, TipoConteudo.HTML);
        } else {
          mensagem.setContent(_texto, TipoConteudo.TEXTO);
        }
      }

    } catch (MessagingException ex) {
      Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
      mensagem = null;
    }

    return mensagem;
  }
 public void envioCorreo(String mensaje, String modo) {
   String subject = "";
   String destination = obtenerParametros("destinatario");
   String mailHost = obtenerParametros("mailHost");
   String source = obtenerParametros("origen");
   if (modo.equals("Fallo")) subject = "Aplicaci\363n de Carga y Validaci\363n de datos. ERROR!!";
   else subject = "Aplicacion de Carga y Validaci\363n de datos. MENSAJE INFORMATIVO";
   Properties properties = new Properties();
   properties.put("mail.smtp.host", mailHost);
   properties.put("mail.from", source);
   Session session = Session.getInstance(properties, null);
   try {
     Message message = new MimeMessage(session);
     InternetAddress address[] = {new InternetAddress(destination)};
     message.setRecipients(javax.mail.Message.RecipientType.TO, address);
     message.setFrom(new InternetAddress(source));
     message.setSubject(subject);
     message.setContent(mensaje + "\n", "text/plain");
     Transport transport = session.getTransport(address[0]);
     transport.connect();
     transport.sendMessage(message, address);
   } catch (Exception e1) {
     e1.printStackTrace();
   }
 }
Beispiel #3
0
 public static void email(
     CallingContext context, String templateName, Map<String, ? extends Object> templateValues) {
   final SMTPConfig config = getSMTPConfig();
   Session session = getSession(config);
   EmailTemplate template = getEmailTemplate(context, templateName);
   try {
     // Instantiate a new MimeMessage and fill it with the required information.
     Message msg = new MimeMessage(session);
     msg.setFrom(new InternetAddress(config.getFrom()));
     String to = renderTemplate(template.getEmailTo(), templateValues);
     if (StringUtils.isBlank(to)) {
       throw RaptureExceptionFactory.create("No emailTo field");
     }
     InternetAddress[] address = {new InternetAddress(to)};
     msg.setRecipients(Message.RecipientType.TO, address);
     msg.setSubject(renderTemplate(template.getSubject(), templateValues));
     msg.setSentDate(new Date());
     msg.setContent(
         renderTemplate(template.getMsgBody(), templateValues), "text/html; charset=utf-8");
     // Hand the message to the default transport service for delivery.
     Transport.send(msg);
   } catch (MessagingException e) {
     log.error("Failed to send email", e);
   }
 }
Beispiel #4
0
  /**
   * 发送邮件 (暂时只支持163邮箱发送)
   *
   * @param fromEmail 发送邮箱
   * @param toEmail 接收邮箱
   * @param emailName 163邮箱登录名
   * @param emailPassword 密码
   * @param title 发送主题
   * @param centent 发送内容
   * @throws Exception
   */
  public static void sendMail(
      String fromEmail,
      String toEmail,
      String emailName,
      String emailPassword,
      String title,
      String centent)
      throws Exception {

    Properties properties = new Properties(); // 创建Properties对象
    properties.setProperty("mail.transport.protocol", "smtp"); // 设置传输协议
    properties.put("mail.smtp.host", "smtp.163.com"); // 设置发信邮箱的smtp地址
    properties.setProperty("mail.smtp.auth", "true"); // 验证
    Authenticator auth = new AjavaAuthenticator(emailName, emailPassword); // 使用验证,创建一个Authenticator
    Session session =
        Session.getDefaultInstance(properties, auth); // 根据Properties,Authenticator创建Session
    Message message = new MimeMessage(session); // Message存储发送的电子邮件信息
    message.setFrom(new InternetAddress(fromEmail));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); // 设置收信邮箱
    // 指定邮箱内容及ContentType和编码方式
    message.setContent(centent, "text/html;charset=utf-8");
    message.setSubject(title); // 设置主题
    message.setSentDate(new Date()); // 设置发信时间
    Transport.send(message); // 发送
  }
  public static void sfSendEmail(String subject, String message) throws Exception {

    String SMTP_HOST_NAME = "smtp.gmail.com";
    String SMTP_PORT = "465";
    // message = "Test Email Notification From Monitor";
    // subject = "Test Email Notification From Monitor";
    String from = "*****@*****.**";
    String[] recipients = {
      "*****@*****.**", "*****@*****.**", "*****@*****.**"
    };
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // String[] recipients = { "*****@*****.**"};
    // String[] recipients = { "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**"};
    // String[] recipients = {"*****@*****.**"};

    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    // props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "*****@*****.**", "els102sensorweb");
              }
            });

    // session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);

    System.out.println("Sucessfully Sent mail to All Users");
  }
 @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
 }
Beispiel #7
0
  public boolean sendMail(String subject, String text, File attachmentFile) {
    try {
      MailAuthenticator auth = new MailAuthenticator(smtpUser, smtpPass);
      Properties properties = new Properties();
      properties.put("mail.smtp.host", smtpServer);
      properties.put("mail.smtp.auth", "true");

      Session session = Session.getDefaultInstance(properties, auth);
      Message msg = new MimeMessage(session);

      MimeMultipart content = new MimeMultipart("alternative");
      MimeBodyPart message = new MimeBodyPart();
      message.setText(text);
      message.setHeader("MIME-Version", "1.0" + "\n");
      message.setHeader("Content-Type", message.getContentType());
      content.addBodyPart(message);
      if (attachmentFile != null) {
        DataSource fileDataSource = new FileDataSource(attachmentFile);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
        messageBodyPart.setFileName(attachmentFile.getName());
        content.addBodyPart(messageBodyPart);
      }
      msg.setContent(content);
      msg.setSentDate(new Date());
      msg.setFrom(new InternetAddress(smtpSender));
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpReceiver, false));
      msg.setSubject(subject);
      Transport.send(msg);
      return true;
    } catch (Exception e) {
      // e.getMessage()
      return false;
    }
  }
Beispiel #8
0
  public static void send(
      String nomContact,
      Integer numFacture,
      Double montantCommande,
      Integer nbLots,
      String typeEnvoi,
      String adresseContact)
      throws Exception {

    Properties props = System.getProperties();
    props.put("mail.smtps.host", "smtp.orange.fr");
    props.put("mail.smtps.auth", "true");

    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress("*****@*****.**"));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(adresseContact, false));

    String corpsMessage =
        "Bonjour "
            + nomContact
            + "\n\n"
            + "votre commande n°"
            + numFacture
            + " d'un montant de "
            + montantCommande
            + "€ TTC vient d'être traitée.\n\n"
            + typeEnvoi
            + " \n\n"
            + "L'équipe du ciné cap vert vous remercie de votre confiance.\n\n\n\n"
            + " P.S.: Retrouvez en pièce jointe le mode d'emploi des chèques cinéma sur notre interface de réservation en ligne";

    msg.setSubject("Votre commande de " + nbLots + " lots de chèques cinéma vient d'être traitée.");
    msg.setHeader("X-Mailer", "Test En-tete");
    msg.setSentDate(new Date());

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

    // create the second message part
    MimeBodyPart mbp2 = new MimeBodyPart();

    // attach the file to the message
    mbp2.attachFile("ccvad.png");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);

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

    SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
    t.connect("smtp.orange.fr", "*****@*****.**", "popcorn21800");
    t.sendMessage(msg, msg.getAllRecipients());
    System.out.println("Réponse: " + t.getLastServerResponse());
    t.close();
  }
Beispiel #9
0
  public static void sendEmail() throws Exception {
    String msgText = "测试邮件";
    // 获取系统属性
    Properties p = System.getProperties();
    // 设置邮件服务器:看看当地是否有邮局
    p.put("mail.smtp.host", "smtp.126.com");
    p.put("mail.smtp.auth", "true");

    // 创建一个邮件会话,准备发送邮件:买信封
    Session s = Session.getDefaultInstance(p, null);
    // 准备一个发送邮件的对象,即邮差
    Transport trans = s.getTransport("smtp");
    // 准备一封邮件:买信纸
    Message m = new MimeMessage(s);
    // 设置邮件的标题,即主题
    m.setSubject("问卷调查用户信息:同学");
    // 设置日期
    m.setSentDate(new Date());
    // 邮件正文
    m.setContent(msgText, "text/html;  charset=gb2312"); // 用于发邮件 设置邮件的标题,即主题
    // 设置发件人:写自己的地址和名字
    Address from = new InternetAddress("*****@*****.**");
    m.setFrom(from);
    // 设置收件人:写对方的地址和名字
    Address to = new InternetAddress("*****@*****.**");
    // 将收件人加到邮件中:将收件人写到信纸上
    m.addRecipient(Message.RecipientType.TO, to);
    // 连接服务器认证
    trans.connect("smtp.126.com", "*****@*****.**", "owenjunefirst");
    // 发送邮件,即投递
    trans.sendMessage(m, m.getAllRecipients());
    System.out.println(msgText + "\n");
  }
Beispiel #10
0
  /** Sends Emails to Customers who have not submitted their Bears */
  public static void BearEmailSendMessage(String msgsubject, String msgText, String msgTo) {
    try {
      BearFrom = props.getProperty("BEARFROM");
      // To = props.getProperty("TO");
      SMTPHost = props.getProperty("SMTPHOST");
      Properties mailprops = new Properties();
      mailprops.put("mail.smtp.host", SMTPHost);

      // create some properties and get the default Session
      Session session = Session.getDefaultInstance(mailprops, null);

      // create a message
      Message msg = new MimeMessage(session);

      // set the from
      InternetAddress from = new InternetAddress(BearFrom);
      msg.setFrom(from);
      InternetAddress[] address = InternetAddress.parse(msgTo);
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject(msgsubject);
      msg.setContent(msgText, "text/plain");
      Transport.send(msg);
    } // end try
    catch (MessagingException mex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    } catch (Exception ex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    }
  } // end BearEmailSendMessage
Beispiel #11
0
 @Override
 public void sendEmail(String id, String total, String email) {
   Properties prop = new Properties();
   prop.setProperty("mail.transport.protocol", "smtp");
   Message message = null;
   Transport transport = null;
   Session session = null;
   try {
     session = Session.getDefaultInstance(prop);
     session.setDebug(true);
     // 创建一封新有邮件
     message = (Message) new MimeMessage(session);
     // 标题、正文内容、发件人地址
     message.setSubject("订单支付成功邮件(系统邮件)");
     message.setContent("订单编号为:" + id + ",金额 为: " + total + ",已经支付成功!", "text/html;charset=utf-8");
     message.setFrom(new InternetAddress("*****@*****.**"));
     // 设置用户名密码,收件人地址,发送邮件
     transport = session.getTransport();
     // 通过用户名与密码, 链接邮件服务器
     transport.connect("smtp.sina.com", "soft03_test", "soft03_test");
     transport.sendMessage(message, new Address[] {new InternetAddress(email)});
   } catch (Exception e) {
     throw new RuntimeException(e);
   } finally {
     try {
       // 关闭客户端(释放资源)
       transport.close();
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
Beispiel #12
0
  /**
   * Sends an email using the given parameters.
   *
   * @param smtp The SMTP server to send from
   * @param from The from-address
   * @param to The to-address
   * @param subj The subject line
   * @param body The message body
   * @throws MessagingException If the email fails to send
   */
  public static void send(
      final String smtp, final String from, final String to, final String subj, final String body)
      throws MessagingException {
    // Silently quit if we are missing any required email information
    if (smtp == null
        || from == null
        || to == null
        || smtp.isEmpty()
        || from.isEmpty()
        || to.isEmpty()) return;

    // Set the host smtp address
    final Properties mailProps = new Properties();
    mailProps.put("mail.smtp.host", smtp);

    // create some properties and get the default Session
    final Session session = Session.getDefaultInstance(mailProps, null);

    // create a message
    final Message msg = new MimeMessage(session);

    // set the from and to address
    final InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    final InternetAddress addressTo = new InternetAddress(to);
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    // set the subject and body
    msg.setSubject(subj);
    msg.setContent(body, "text/plain");

    // send the email message
    Transport.send(msg);
  }
  public void postMail(String recipients[], String subject, String message, String from)
      throws MessagingException {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.timeout", 60000);

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/html");
    Transport.send(msg);
  }
  @Override
  public void sendAsHtml(
      String subject, String html, Collection<String> recipients, Map<String, Object> htmlParams)
      throws Exception {
    Address[] addresses = new Address[recipients.size()];
    Iterator<String> iterator = recipients.iterator();
    int i = 0;
    while (iterator.hasNext()) {
      addresses[i] = new InternetAddress(iterator.next());
      i++;
    }

    Template template = configuration.getTemplate(html);
    Writer writer = new StringWriter();
    template.process(htmlParams, writer);

    BodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(writer.toString(), "text/html");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(bodyPart);

    Message message = new MimeMessage(session);
    message.setFrom();
    message.setRecipients(Message.RecipientType.TO, addresses);
    message.setSubject(subject);
    message.setContent(multipart, "text/html");

    Transport.send(message);
  }
Beispiel #15
0
  /**
   * 构建邮件
   *
   * @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;
  }
Beispiel #16
0
  public static void SendMail(String to, String subject, String Content) {
    try {

      // setup the mail server properties
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");

      // set up the message
      Session session = Session.getInstance(props);

      Message message = new MimeMessage(session);

      // add a TO address
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

      // add a multiple CC addresses
      // message.setRecipients(Message.RecipientType.CC,
      // InternetAddress.parse("[email protected],[email protected]"));

      message.setSubject(subject);
      message.setContent(Content, "text/plain");

      Transport transport = session.getTransport("smtp");
      transport.connect("smtp.gmail.com", 587, "aaa", "pass");
      transport.sendMessage(message, message.getAllRecipients());
      // System.out.println("Send email via gmail...");
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
Beispiel #17
0
  public void send(String mailto, String subject, String textMessage, String contentType)
      throws FileNotFoundException, MessagingException {
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    Properties props = new Properties();
    props.put("mail.smtp.user", smtpUsername);
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", smtpPort);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtps.auth", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.socketFactory.port", smtpPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.ssl", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session smtpSession = Session.getInstance(props, auth);
    smtpSession.setDebug(true);

    Message message = new MimeMessage(smtpSession);
    InternetAddress[] address = {new InternetAddress(mailto)};
    message.setRecipients(Message.RecipientType.TO, address);
    message.setSubject(subject);
    message.setSentDate(new Date());
    message.setContent(textMessage, contentType);

    Transport tr = smtpSession.getTransport("smtp");
    tr.connect(smtpHost, smtpUsername, smtpPassword);
    tr.sendMessage(message, message.getAllRecipients());
    tr.close();
  }
Beispiel #18
0
  @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());
    }
  }
Beispiel #19
0
  /*
   * (non-Javadoc)
   *
   * @see org.mule.tck.providers.AbstractMessageAdapterTestCase#getValidMessage()
   */
  public Object getValidMessage() throws Exception {
    if (message == null) {
      message = new MimeMessage(Session.getDefaultInstance(new Properties()));
      message.setContent("Test Email Message", "text/plain");
    }

    return message;
  }
Beispiel #20
0
  /**
   * 发送邮件不带附件
   *
   * @author bxmen
   * @param user 用户名
   * @param password 密码
   * @param smtpHost 邮件服务器
   * @param userName 发件人姓名
   * @param toAddr 接收者
   * @param subject 邮件主题
   * @param body 邮件内容
   * @summary
   */
  public void send(
      String user,
      String password,
      String smtpHost,
      String userName,
      String toAddr,
      String subject,
      String body) {
    try {
      Authenticator auth = new MailAuthenticator(user, password);

      Properties props = new Properties();
      // 指定SMTP服务器,邮件通过它来投递
      props.put("mail.smtp.host", smtpHost);
      props.put("mail.smtp.auth", "true");

      Session session = Session.getInstance(props, auth);
      Message msg = new MimeMessage(session);
      // 指定发信人中文名称
      if (null != userName && !userName.trim().equals("")) {
        msg.setFrom(new InternetAddress(user, userName));
      } else {
        msg.setFrom(new InternetAddress(user));
      }

      // 指定收件人,多人时用逗号分隔
      InternetAddress[] tos = InternetAddress.parse(toAddr);
      msg.setRecipients(Message.RecipientType.TO, tos);
      // 标题//转码BASE64Encoder
      String smtpEncode = "";
      if (null == smtpEncode || smtpEncode.trim().equals("")) {
        smtpEncode = "utf-8";
      }
      ((MimeMessage) msg).setSubject(subject, smtpEncode);
      // 得到中文标题for linux,windows下不用;
      // 内容
      msg.setText(body);
      // 发送时间
      msg.setSentDate(new Date());
      // 内容类型Content-type
      String smtpME = "";
      if (null == smtpME || smtpME.trim().equals("")) {
        smtpME = "utf-8";
      }
      msg.setContent(body, "text/html;charset=" + smtpME);
      // 发送
      Transport.send(msg);
    } catch (MessagingException e) {
      if (DEBUG) {
        e.printStackTrace();
      }
    } catch (UnsupportedEncodingException e) {
      if (DEBUG) {
        e.printStackTrace();
      }
    }
  }
Beispiel #21
0
  public static void sendMail(String dest, String oggetto, String testoEmail)
      throws MessagingException {
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    // Creazione di una mail session
    // Get a Properties object

    Properties props = System.getProperties();

    props.setProperty("mail.smtp.host", "smtp.gmail.com");

    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);

    props.setProperty("mail.smtp.socketFactory.fallback", "false");

    props.setProperty("mail.smtp.port", "465");

    props.setProperty("mail.smtp.socketFactory.port", "465");

    props.put("mail.smtp.auth", "true");

    props.put("mail.debug", "true");

    final String username = "******";

    final String password = "******";

    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication(username, password);
              }
            });

    // — Create a new message –

    Message msg = new MimeMessage(session);

    // — Set the FROM and TO fields –

    msg.setFrom(new InternetAddress(username + ""));

    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(dest, false));

    msg.setSubject(oggetto);

    msg.setContent(testoEmail, "text/html; charset=utf-8");

    msg.setSentDate(new Date());

    Transport.send(msg);
  }
Beispiel #22
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);
    }
  }
  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();
    }
  }
Beispiel #24
0
 private Message composeMessage(Email email, String contentType) throws EmailCompositionException {
   Message message = new MimeMessage(session);
   try {
     message.setFrom(createInternetAddress(email.getFrom()));
     setRecipients(email, message);
     message.setSubject(email.getSubject());
     message.setContent(email.getMessageText(), contentType);
   } catch (Exception e) {
     throw new EmailCompositionException(e);
   }
   return message;
 }
  /** Since Openbravo 3.0MP9 only {@link #sendEmail()} is used for the full email sending cycle */
  @Deprecated
  public void sendSimpleEmail(
      Session session,
      String from,
      String to,
      String bcc,
      String subject,
      String body,
      String attachmentFileLocations)
      throws PocException {
    try {
      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));

      message.setRecipients(Message.RecipientType.TO, getAddressesFrom(to.split(",")));

      if (bcc != null)
        message.setRecipients(Message.RecipientType.BCC, getAddressesFrom(bcc.split(",")));

      message.setSubject(subject);

      // Content consists of 2 parts, the message body and the attachment
      // We therefore use a multipart message
      Multipart multipart = new MimeMultipart();

      // Create the message part
      MimeBodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(body);
      multipart.addBodyPart(messageBodyPart);

      // Create the attachment parts
      if (attachmentFileLocations != null) {
        String attachments[] = attachmentFileLocations.split(",");

        for (String attachment : attachments) {
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(attachment);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(attachment.substring(attachment.lastIndexOf("/") + 1));
          multipart.addBodyPart(messageBodyPart);
        }
      }

      message.setContent(multipart);

      // Send the email
      Transport.send(message);
    } catch (AddressException exception) {
      throw new PocException(exception);
    } catch (MessagingException exception) {
      throw new PocException(exception);
    }
  }
Beispiel #26
0
  /**
   * Send an HTML email.
   *
   * @param recipients The list of email recipients where the email should be sent to.
   * @param subject The email subject.
   * @param message The HTML message.
   * @param fromAddress The sender email address that should be set on the email.
   * @param fromName The sender name that should be set on the email.
   * @throws MessagingException Any error that might occur on sending the message.
   */
  public static void sendEmail(
      final String[] recipients,
      final String subject,
      final String message,
      final String fromAddress,
      final String fromName)
      throws MessagingException {
    final boolean debug = false;

    // Set the host smtp address
    final Properties props = new Properties();
    try {
      props.load(
          MailUtils.class.getResourceAsStream(
              "/eu/scape_project/watch/notification/email/config/mail.properties"));
    } catch (final IOException e) {
      LOG.error("Could not find mail.properties, using localhost as SMTP host", e);
      props.put("mail.smtp.host", "localhost");
    } catch (final NullPointerException e) {
      LOG.error("Could not find mail.properties, using localhost as SMTP host", e);
      props.put("mail.smtp.host", "localhost");
    }

    // create some properties and get the default Session
    final Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);

    // create a message
    final Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom;
    try {
      addressFrom = new InternetAddress(fromAddress, fromName);
    } catch (final UnsupportedEncodingException e) {
      addressFrom = new InternetAddress(fromAddress);
    }
    msg.setFrom(addressFrom);

    final InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Optional: You can also set your custom headers
    // msg.addHeader("MyHeaderName", "myHeaderValue");

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/html; charset=\"UTF-8\"");
    Transport.send(msg);
  }
Beispiel #27
0
 /**
  * 以HTML格式发送邮件
  *
  * @param entity 待发送的邮件信息
  */
 public boolean sendHtmlMail(MailSenderModel entity) {
   // 判断是否需要身份认证
   MyAuthenticator authenticator = null;
   // 如果需要身份认证,则创建一个密码验证器
   if (entity.isValidate()) {
     authenticator = new MyAuthenticator(entity.getUserName(), entity.getPassword());
   }
   // 根据邮件会话属性和密码验证器构造一个发送邮件的session
   Session sendMailSession = Session.getDefaultInstance(entity.getProperties(), authenticator);
   try {
     // 根据session创建一个邮件消息
     Message mailMessage = new MimeMessage(sendMailSession);
     // 创建邮件发送者地址
     Address from = new InternetAddress(entity.getFromAddress());
     // 设置邮件消息的发送者
     mailMessage.setFrom(from);
     // 创建邮件的接收者地址,并设置到邮件消息中
     // Address to = new InternetAddress();
     // Message.RecipientType.TO属性表示接收者的类型为TO
     mailMessage.setRecipients(
         Message.RecipientType.TO, InternetAddress.parse(entity.getToAddress()));
     // 抄送
     if (entity.getCcAddress() != null && !"".equals(entity.getCcAddress())) {
       mailMessage.setRecipients(
           Message.RecipientType.CC, InternetAddress.parse(entity.getCcAddress()));
     }
     // 暗送
     if (entity.getBccAddress() != null && !"".equals(entity.getBccAddress())) {
       mailMessage.setRecipients(
           Message.RecipientType.BCC, InternetAddress.parse(entity.getBccAddress()));
     }
     // 设置邮件消息的主题
     mailMessage.setSubject(entity.getSubject());
     // 设置邮件消息发送的时间
     mailMessage.setSentDate(new Date());
     // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
     Multipart mainPart = new MimeMultipart();
     // 创建一个包含HTML内容的MimeBodyPart
     BodyPart html = new MimeBodyPart();
     // 设置HTML内容
     html.setContent(entity.getContent(), "text/html; charset=" + DEFAULT_ENCODING);
     mainPart.addBodyPart(html);
     // 将MiniMultipart对象设置为邮件内容
     mailMessage.setContent(mainPart);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
  public void doMail(String mailTo, String mailFrom) throws Exception {
    Message msg = new MimeMessage(myMailSession);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(mailFrom);
    msg.setFrom(addressFrom);
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
    msg.setSubject("Jetty Mail Test Succeeded");
    msg.setContent(
        "The test of Jetty Mail @ " + new Date() + " has been successful.", "text/plain");
    msg.addHeader("Date", dateFormat.format(new Date()));
    Transport.send(msg);
  }
  private Message createMessage(String content) {

    Message message = new MimeMessage(session);
    try {
      message.setFrom(new InternetAddress(config.getUsername()));
      message.setRecipients(
          Message.RecipientType.TO, InternetAddress.parse(config.getEmailToNotificate()));
      message.setSubject(SUBJECT);
      message.setContent(content, "text/html; charset=utf-8");
    } catch (MessagingException e) {
      LOG.error("Error during message creating", e);
    }
    return message;
  }
  public void sendVerificationEmailLocally(String recipients, String verificationLink) {

    String body = String.format(bodyTemplate, verificationLink);

    log.debug("Sending email to recipients={}, subject={}, body={}", recipients, subject, body);

    // Gmail properties
    Properties smtpProperties = new Properties();

    smtpProperties.put("mail.smtp.host", smtpHost);
    smtpProperties.put("mail.smtp.socketFactory.port", smtpPort);
    smtpProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    smtpProperties.put("mail.smtp.auth", "true");
    smtpProperties.put("mail.smtp.port", "465");

    Session session =
        Session.getInstance(
            smtpProperties,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
              }
            });

    try {
      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(fromAddress));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
      message.setSubject(subject);

      message.setContent(body, "text/html; charset=utf-8");
      Transport.send(message);
      log.info("Sent email to " + recipients);
    } catch (MessagingException e) {
      String smtpInfo =
          "Error sending email. SMTP_HOST="
              + smtpHost
              + ", SMTP_PORT="
              + smtpPort
              + ", smtpUsername="******", subject="
              + subject;
      if (e.getCause() instanceof AuthenticationFailedException) {
        log.warn(
            "Failed to send mail due to missconfiguration? Reason {}", e.getCause().getMessage());
      }
      throw new RuntimeException(smtpInfo, e);
    }
  }