Example #1
0
  /** 根据传入的 Seesion 对象创建混合型的 MIME消息 */
  public MimeMessage createMessage(Session session) throws Exception {
    String from = "*****@*****.**";
    String to = "*****@*****.**";
    String subject = "创建内含附件、图文并茂的邮件!";
    String body =
        "<h4>内含附件、图文并茂的邮件测试!!!</h4> </br>"
            + "<a href = http://haolloyin.blog.51cto.com/> 蚂蚁</a></br>"
            + "<img src = \"cid:logo_jpg\"></a>";

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(subject);

    // 创建邮件的各个 MimeBodyPart 部分
    MimeBodyPart attachment01 = createAttachment("F:\\java\\Snake.java");
    MimeBodyPart attachment02 = createAttachment("F:\\java\\meng.mp3");
    MimeBodyPart content = createContent(body, "F:\\java\\logo.jpg");

    // 将邮件中各个部分组合到一个"mixed"型的 MimeMultipart 对象
    MimeMultipart allPart = new MimeMultipart("mixed");
    allPart.addBodyPart(attachment01);
    allPart.addBodyPart(attachment02);
    allPart.addBodyPart(content);

    // 将上面混合型的 MimeMultipart 对象作为邮件内容并保存
    msg.setContent(allPart);
    msg.saveChanges();
    return msg;
  }
  public static void main(String args[]) throws Exception {
    //
    // create the generator for creating an smime/compressed message
    //
    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();

    //
    // create the base for our message
    //
    MimeBodyPart msg = new MimeBodyPart();

    msg.setText("Hello world!");

    MimeBodyPart mp = gen.generate(msg, new ZlibCompressor());

    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);

    Address fromUser = new InternetAddress("\"Eric H. Echidna\"<*****@*****.**>");
    Address toUser = new InternetAddress("*****@*****.**");

    MimeMessage body = new MimeMessage(session);
    body.setFrom(fromUser);
    body.setRecipient(Message.RecipientType.TO, toUser);
    body.setSubject("example compressed message");
    body.setContent(mp.getContent(), mp.getContentType());
    body.saveChanges();

    body.writeTo(new FileOutputStream("compressed.message"));
  }
  public boolean send() {
    try {
      Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", "smtp.gmail.com");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");
      props.put("mail.debug", "true");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.socketFactory.fallback", "false");
      Session session = Session.getDefaultInstance(props, new GJMailAuthenticator());
      session.setDebug(true);
      Transport transport = session.getTransport();
      InternetAddress addressFrom = new InternetAddress("*****@*****.**");
      MimeMessage message = new MimeMessage(session);
      message.setSender(addressFrom);
      message.setSubject(subject);
      message.setContent(text, "text/html");
      InternetAddress addressTo = new InternetAddress(to);
      message.setRecipient(Message.RecipientType.TO, addressTo);
      transport.connect();
      Transport.send(message);
      transport.close();
      System.out.println("DONE");

    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }
Example #4
0
  public synchronized void sendImage(
      String subject, String body, String sender, String recipients, File attachment)
      throws Exception {

    try {
      MimeMessage message = new MimeMessage(session);
      message.setSender(new InternetAddress(sender));
      message.setSubject(subject);

      MimeBodyPart mbp1 = new MimeBodyPart();
      mbp1.setText(body);

      MimeBodyPart mbp2 = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(attachment);
      mbp2.setDataHandler(new DataHandler(fds));
      mbp2.setFileName(fds.getName());

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

      message.setContent(mp);

      if (recipients.indexOf(',') > 0)
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
      else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
      Transport.send(message);
    } catch (Exception e) {
      Log.e("GmalSender", "Exception", e);
    }
  }
Example #5
0
 protected void setMessageAddresses(MimeMessage mail, ItemOrder order)
     throws AddressException, MessagingException {
   InternetAddress destination = InternetAddress.parse(destinationAddress)[0];
   mail.setFrom(destination);
   mail.setReplyTo(InternetAddress.parse(order.getCustomerEmail()));
   mail.setRecipient(RecipientType.TO, destination);
 }
  public void enviarEmail() {
    FacesContext context = FacesContext.getCurrentInstance();
    AutenticaUsuario autenticaUsuario =
        new AutenticaUsuario(GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL);
    Session session = Session.getDefaultInstance(this.configuracaoEmail(), autenticaUsuario);
    session.setDebug(true);

    try {

      Transport envio = null;
      MimeMessage email = new MimeMessage(session);
      email.setRecipient(Message.RecipientType.TO, new InternetAddress(this.para));
      email.setFrom(new InternetAddress(this.de));
      email.setSubject(this.assunto);
      email.setContent(this.mensagem, "text/plain");
      email.setSentDate(new Date());
      envio = session.getTransport("smtp");
      envio.connect(GmailBean.SERVIDOR_SMTP, GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL);
      email.saveChanges();
      envio.sendMessage(email, email.getAllRecipients());
      envio.close();

      context.addMessage(null, new FacesMessage("E-mail enviado com sucesso"));

    } catch (AddressException e) {
      FacesMessage msg =
          new FacesMessage("Erro ao montar mensagem de e-mail! Erro: " + e.getMessage());
      context.addMessage(null, msg);
      return;
    } catch (MessagingException e) {
      FacesMessage msg = new FacesMessage("Erro ao enviar e-mail! Erro: " + e.getMessage());
      context.addMessage(null, msg);
      return;
    }
  }
Example #7
0
  public void mail(String toAddress, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.ssl.enable", true);
    Authenticator authenticator = null;
    if (login) {
      props.put("mail.smtp.auth", true);
      authenticator =
          new Authenticator() {
            private PasswordAuthentication pa = new PasswordAuthentication(username, password);

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
              return pa;
            }
          };
    }

    Session s = Session.getInstance(props, authenticator);
    s.setDebug(debug);
    MimeMessage email = new MimeMessage(s);
    try {
      email.setFrom(new InternetAddress(from));
      email.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
      email.setSubject(subject);
      email.setSentDate(new Date());
      email.setText(body);
      Transport.send(email);
    } catch (MessagingException ex) {
      ex.printStackTrace();
    }
  }
  public void testAttachments() throws Exception {
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "localhost");
    props.setProperty("mail.smtp.port", SMTP_PORT + "");
    Session session = Session.getInstance(props);

    MimeMessage baseMsg = new MimeMessage(session);
    MimeBodyPart bp1 = new MimeBodyPart();
    bp1.setHeader("Content-Type", "text/plain");
    bp1.setContent("Hello World!!!", "text/plain; charset=\"ISO-8859-1\"");

    // Attach the file
    MimeBodyPart bp2 = new MimeBodyPart();
    FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH);
    DataHandler dh = new DataHandler(fileAttachment);
    bp2.setDataHandler(dh);
    bp2.setFileName(fileAttachment.getName());

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(bp1);
    multipart.addBodyPart(bp2);

    baseMsg.setFrom(new InternetAddress("Ted <*****@*****.**>"));
    baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**"));
    baseMsg.setSubject("Test Big attached file message");
    baseMsg.setContent(multipart);
    baseMsg.saveChanges();

    LOG.debug("Send started");
    Transport t = new SMTPTransport(session, new URLName("smtp://*****:*****@example.org")});
    t.close();
    started = System.currentTimeMillis() - started;
    LOG.info("Elapsed ms = " + started);

    WiserMessage msg = server.getMessages().get(0);

    assertEquals(1, server.getMessages().size());
    assertEquals("*****@*****.**", msg.getEnvelopeReceiver());

    File compareFile = File.createTempFile("attached", ".tmp");
    LOG.debug("Writing received attachment ...");

    FileOutputStream fos = new FileOutputStream(compareFile);
    ((MimeMultipart) msg.getMimeMessage().getContent())
        .getBodyPart(1)
        .getDataHandler()
        .writeTo(fos);
    fos.close();
    LOG.debug("Checking integrity ...");
    assertTrue(checkIntegrity(new File(BIGFILE_PATH), compareFile));
    LOG.debug("Checking integrity DONE");
    compareFile.delete();
    msg.dispose();
  }
Example #9
0
 public void sendEmailUsingJava(String to, String content, String subjectContext) {
   // int smtpPort = 465;
   // int smtpPort = 587;
   // String smtpHost = "smtp.gmail.com";
   // int smtpPort = 25;
   // String smtpHost = "exsmtp.wvu.edu";
   String subject = constants.getString(subjectContext);
   int smtpPort = Integer.parseInt(constants.getString("smtpPort"));
   String smtpHost = constants.getString("smtpHost");
   String urPassword = constants.getString("password");
   String from = constants.getString("emailaddress");
   // String content = contentText;
   // Create a mail session
   java.util.Properties props = new java.util.Properties();
   props = System.getProperties();
   props.put("mail.smtp.host", smtpHost);
   // props.put("mail.smtp.starttls.enable", "true");
   props.put("mail.smtps.auth", "true");
   SmtpAuthenticator authentication = new SmtpAuthenticator();
   // Session session = Session.getInstance(props, null);
   Session session = Session.getInstance(props, authentication);
   session.setDebug(true);
   // Construct the message
   try {
     MimeMessage msg = new MimeMessage(session);
     msg.setFrom(new InternetAddress(from));
     msg.setRecipient(RecipientType.TO, new InternetAddress(to));
     msg.setSubject(subject);
     msg.setText(content);
     msg.setSentDate(new Date());
     Transport tr = null;
     tr = session.getTransport("smtp");
     tr.connect(smtpHost, smtpPort, from, urPassword);
     tr.sendMessage(msg, msg.getAllRecipients());
   } catch (AddressException e) {
     System.out.println(e.getClass().getName() + ": " + e.getMessage());
     Log.info(e.getClass().getName() + ": " + e.getMessage());
     StackTraceElement[] trace = e.getStackTrace();
     for (int i = 0; i < trace.length; i++) {
       System.out.println("\t" + trace[i].toString());
       Log.info("\n\t" + trace[i].toString());
     }
     e.printStackTrace();
   } catch (MessagingException e) {
     System.out.println(e.getClass().getName() + ": " + e.getMessage());
     Log.info(e.getClass().getName() + ": " + e.getMessage());
     StackTraceElement[] trace = e.getStackTrace();
     for (int i = 0; i < trace.length; i++) {
       System.out.println("\t" + trace[i].toString());
       Log.info("\n\t" + trace[i].toString());
     }
     e.printStackTrace();
   }
 }
Example #10
0
 public synchronized void sendMail(String subject, String body, String sender, String recipients)
     throws Exception {
   MimeMessage message = new MimeMessage(session);
   DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
   message.setSender(new InternetAddress(sender));
   message.setSubject(subject);
   message.setDataHandler(handler);
   if (recipients.indexOf(',') > 0)
     message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
   else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
   Transport.send(message);
 }
  private Message buildErrorMessage() throws MessagingException {
    MimeMessage errorMessage = new MimeMessage(mailSetup.getSession(this.errorMailProperties));

    errorMessage.setRecipient(
        Message.RecipientType.TO,
        new InternetAddress(this.errorMailMessages.getString("serviceFailToEmailAddress")));
    errorMessage.setFrom(
        new InternetAddress(this.errorMailMessages.getString("serviceFailFromEmailAddress")));
    errorMessage.setSubject(buildErrorMessageSubject(this.service), "utf-8");
    errorMessage.setContent(buildErrorMessageContent(this.service), "text/plain; charset=utf-8");

    return errorMessage;
  }
  public void sendEMailToUser(ICFSecuritySecUserObj toUser, String msgSubject, String msgBody)
      throws IOException, MessagingException, NamingException {

    final String S_ProcName = "sendEMailToUser";

    Properties props = System.getProperties();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFInternet25SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpEmailFrom");
    }

    smtpUsername = (String) ctx.lookup("java:comp/env/CFInternet25SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFInternet25SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpPassword");
    }

    Session emailSess =
        Session.getInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
              }
            });

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(toUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject((msgSubject != null) ? msgSubject : "No subject");
    msg.setSentDate(new Date());
    msg.setContent(msgBody, "text/html");
    msg.saveChanges();

    Transport.send(msg);
  }
Example #13
0
  public static Boolean sendFeedbackEmail(CustomerFeedback customerFeedback) {

    Properties mailProps = new Properties();
    mailProps.setProperty("mail.smtp.host", onemenuMailHostName);
    mailProps.setProperty("mail.smtp.starttls.enable", "true");
    mailProps.setProperty("mail.smtp.auth", "true");
    mailProps.setProperty("mail.smtp.quitwait", "false");
    mailProps.setProperty("mail.smtp.ssl.trust", "*");

    Authenticator authenticator = new EmailAuthenticator(onemenuMailAddress, onemenuPassword);

    javax.mail.Session mailSession =
        javax.mail.Session.getDefaultInstance(mailProps, authenticator);

    try {

      Address fromAddress = new InternetAddress(onemenuMailAddress);
      Address toAddress = new InternetAddress(onemenuMailAddress);
      // modify by file 本处不用使用StringBuffer,Stringbuffer
      // 是线程安全的,性能不如StringBuilder(所有本身是线程安全的代码都不应该使用StringBuffer)
      // StringBuffer contentBuffer = new StringBuffer();
      StringBuilder contentBuilder = new StringBuilder();
      contentBuilder
          .append("<p>" + customerFeedback.getmCustomerEmail() + "</p>")
          .append("<p>" + customerFeedback.getmCustomerName() + ":</p>")
          .append("<p>" + customerFeedback.getmContent() + "</p>");
      String content = contentBuilder.toString();

      MimeMessage msg = new MimeMessage(mailSession);
      msg.setFrom(fromAddress);
      msg.setSubject("[OneMenu Feedback] ");
      msg.setSentDate(new Date());
      msg.setContent(content, "text/html;charset=utf-8");
      msg.setRecipient(RecipientType.TO, toAddress);

      /*
       * Transport transport = session.getTransport("smtp"); transport.connect("smtp.163.com",
       * userName, password); transport.sendMessage(msg,msg.getAllRecipients());
       * transport.close();
       */

      Transport.send(msg);
      if (LOGGER.isDebugEnabled()) LOGGER.debug("Send feedback email.");

    } catch (MessagingException e) {
      LOGGER.error("", e);
    }

    return true;
  }
Example #14
0
  public synchronized void sendMail(Mail m) throws MessagingException {

    MimeMessage message = new MimeMessage(session);
    DataHandler handler =
        new DataHandler(new ByteArrayDataSource(m.getBody().getBytes(), "text/plain"));
    message.setSender(new InternetAddress(m.getSender()));
    message.setSubject(m.getSubject());
    message.setDataHandler(handler);
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(m.getRecipient()));
    Transport tr = session.getTransport("smtp");
    tr.connect(user, password);
    tr.send(message);
    tr.close();
  }
Example #15
0
 // sending the mail
 private boolean sendMail(String subject, String message) {
   MimeMessage msg = new MimeMessage(session);
   try {
     msg.setFrom(from);
     msg.setSubject(subject);
     msg.setText(message);
     msg.setRecipient(Message.RecipientType.TO, to);
     Transport.send(msg);
     return true;
   } catch (Exception e) {
     ConsoleUtils.printException(e, Core.NAME, "Can't send mail!");
     return false;
   }
 }
  public boolean sendWithAttachment(File attachFile) {
    try {
      Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", "smtp.gmail.com");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");
      props.put("mail.debug", "true");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.socketFactory.fallback", "false");
      Session session = Session.getDefaultInstance(props, new GJMailAuthenticator());
      session.setDebug(true);
      Transport transport = session.getTransport();
      InternetAddress addressFrom = new InternetAddress("*****@*****.**");
      MimeMessage message = new MimeMessage(session);
      message.setSender(addressFrom);
      message.setSubject(subject);
      // create the message part
      MimeBodyPart messageBodyPart = new MimeBodyPart();
      MimeBodyPart messageAttachmentPart = new MimeBodyPart();
      // fill message
      messageBodyPart.setContent(text, "text/html");
      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);
      // Part two is attachment
      messageAttachmentPart = new MimeBodyPart();
      DataSource source = new FileDataSource(attachFile.getAbsolutePath());
      messageAttachmentPart.setDataHandler(new DataHandler(source));
      messageAttachmentPart.setFileName(attachFile.getName());
      multipart.addBodyPart(messageAttachmentPart);
      // Put parts in message
      message.setContent(multipart);
      InternetAddress addressTo = new InternetAddress(to);
      message.setRecipient(Message.RecipientType.TO, addressTo);
      transport.connect();
      Transport.send(message);
      transport.close();
      System.out.println("DONE");

    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }
Example #17
0
 /**
  * Factory method to add a message by specifying its fields.
  *
  * <p>To use more advanced message features, use the <code>addMessage(Message message)</code>
  * method.
  *
  * <p>If parts of the message are invalid (ie, the toEmail is null) the message won't be sent.
  *
  * @param toName the name of the recipient of this email.
  * @param toEmail the email address of the recipient of this email.
  * @param fromName the name of the sender of this email.
  * @param fromEmail the email address of the sender of this email.
  * @param subject the subject of the email.
  * @param body the body of the email.
  * @param format text/html or text/plain
  */
 public void addMessage(
     String toName,
     String toEmail,
     String fromName,
     String fromEmail,
     String subject,
     String body,
     String format) {
   // Check for errors in the given fields:
   if (toEmail == null || fromEmail == null || subject == null || body == null) {
     System.err.println("Error sending email in EmailTask.java: " + "Invalid fields.");
   } else {
     try {
       MimeMessage message = createMessage();
       Address to = null;
       Address from = null;
       if (toEmail != null) {
         if (toName != null) {
           to = new InternetAddress(toEmail, toName);
         } else {
           to = new InternetAddress(toEmail);
         }
       }
       if (fromEmail != null) {
         if (fromName != null) {
           from = new InternetAddress(fromEmail, fromName);
         } else {
           from = new InternetAddress(fromEmail);
         }
       }
       message.setRecipient(Message.RecipientType.TO, to);
       message.setFrom(from);
       message.setSubject(subject);
       message.setText(body, "UTF-8");
       // more details: http://www.vipan.com/htdocs/javamail.html
       message.setHeader("Content-Type", format + "; charset=utf-8");
       /**
        * msg.setDataHandler(new DataHandler( new ByteArrayDataSource(mail.getContent(),
        * "text/html"))); msg.setHeader("X-Mailer", "JavaMailer");
        */
       addMessage(message);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Example #18
0
 public synchronized void sendMail(String subject, String body, String sender, String recipients)
     throws Exception {
   try {
     message = new MimeMessage(session);
     DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
     message.setSender(new InternetAddress(sender));
     message.setSubject(subject);
     message.setDataHandler(handler);
     if (recipients.indexOf(',') > 0)
       message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
     else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
     Thread Subthread = new Thread(mutiThread); // 開一個新的線程,去執行網路連線
     Subthread.start();
   } catch (Exception e) {
     Log.v("ErrorMail", e.toString());
   }
 }
Example #19
0
  private MimeMessage createMessage(InternetAddress fromAddress, InternetAddress toAddress) {
    MimeMessage msg;

    msg = new MimeMessage(mailSession);

    try {
      // sender the recipient will see
      msg.setFrom(fromAddress);
      // sender the mail system will verify against etc.
      msg.setSender(new InternetAddress(SpecialSender.NOBODY.toString()));
      msg.setRecipient(Message.RecipientType.TO, toAddress);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }

    return msg;
  }
Example #20
0
  public boolean sendMultipartMail(final MailOption mailOption) {
    try {
      Properties props = System.getProperties();
      props.put("mail.transport.protocol", "smtp");
      // props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.host", "smtp.bcel.com.la");
      props.put("mail.smtp.port", "25");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.starttls.required", "true");

      // Session session = Session.getInstance(props, null);

      Session session =
          Session.getDefaultInstance(
              props,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                  // return new PasswordAuthentication("dineshvgsmadurai","VGS@1234");
                  return new PasswordAuthentication("*****@*****.**", "bcel@123");
                }
              });

      try {
        MimeMessage msg = new MimeMessage(session);

        System.out.println("mailOption : " + mailOption.getTo()[0]);

        // msg.setFrom(new InternetAddress("*****@*****.**"));
        msg.setFrom(new InternetAddress("*****@*****.**"));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailOption.getTo()[0]));
        msg.setSubject(mailOption.getSubject());
        msg.setContent(mailOption.getMultipart());

        Transport.send(msg);

      } catch (MessagingException e) {
        e.printStackTrace();
      }

    } catch (Exception e) {

    }
    return true;
  }
Example #21
0
  public static void main(String[] a) {

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

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

    Properties props = new Properties();

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

    props.put("mail.smtp.host", "mail.vms.com.vn");

    String to = "*****@*****.**";
    String subject = "abc";
    String body = createBody("aaaaaaa");
    /*Doan nay ben em dang dung IP*/

    Session session =
        Session.getInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
              }
            });

    try {

      MimeMessage mimeMessage = new MimeMessage(session);
      mimeMessage.setHeader("Content-Type", "text/html; charset=UTF-8");
      mimeMessage.setFrom(new InternetAddress(username));
      mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
      mimeMessage.setSubject(subject, "utf-8");
      mimeMessage.setContent(body, "text/html; charset=UTF-8");

      Transport.send(mimeMessage);

      System.out.println("Done");

    } catch (MessagingException e) {

      throw new RuntimeException(e);
    }
  }
Example #22
0
 private MimeMessage createMimeMessage() throws RejectExceptionExt {
   try {
     Properties props = new Properties();
     Session session = Session.getInstance(props);
     MimeMessage message = new MimeMessage(session);
     try {
       message.setFrom(new InternetAddress(from));
       message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
     } catch (AddressException e) {
       throw new ConfigurationException(e);
     }
     message.setSubject(subject, "UTF-8");
     message.setText("");
     return message;
   } catch (MessagingException e) {
     logger.error("Cannot create a mail list MimeMessage", e);
     throw new RejectExceptionExt(EnhancedStatus.TRANSIENT_LOCAL_ERROR_IN_PROCESSING);
   }
 }
Example #23
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;
  }
 @Override
 protected void sendReminder(CalendarItem calItem, Invite invite) throws Exception {
   Account account = calItem.getAccount();
   Locale locale = account.getLocale();
   TimeZone tz = Util.getAccountTimeZone(account);
   MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSmtpSession(account));
   String to = account.getAttr(Provisioning.A_zimbraCalendarReminderDeviceEmail);
   if (to == null) {
     ZimbraLog.scheduler.info(
         "Unable to send calendar reminder sms since %s is not set",
         Provisioning.A_zimbraCalendarReminderDeviceEmail);
     return;
   }
   mm.setRecipient(javax.mail.Message.RecipientType.TO, new JavaMailInternetAddress(to));
   mm.setText(getText(calItem, invite, locale, tz), MimeConstants.P_CHARSET_UTF8);
   mm.saveChanges();
   MailSender mailSender = calItem.getMailbox().getMailSender();
   mailSender.setSaveToSent(false);
   mailSender.sendMimeMessage(null, calItem.getMailbox(), mm);
 }
Example #25
0
  public static void exec(String mailbox, String title, String content) throws Exception {

    String mail_from = MailBean.mailAddress; // mailbox 发送到哪 title 标题
    Properties props = new Properties();

    props.put("mail.smtp.host", MailBean.mailServer);

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

    Session s = Session.getInstance(props);

    s.setDebug(true);

    MimeMessage message = new MimeMessage(s);

    InternetAddress from = new InternetAddress(mail_from);

    message.setFrom(from);

    InternetAddress to = new InternetAddress(mailbox);

    message.setRecipient(Message.RecipientType.TO, to);

    message.setSubject(title);

    message.setText(content);

    message.setContent(content, "text/html;charset=gbk");

    message.setSentDate(new Date());

    message.saveChanges();

    Transport transport = s.getTransport("smtp");

    transport.connect(MailBean.mailServer, MailBean.mailCount, MailBean.mailPassword);

    transport.sendMessage(message, message.getAllRecipients());

    transport.close();
  }
Example #26
0
    /**
     * Send an email to the admin address
     *
     * @throws IOException
     * @throws ServletException
     * @throws InterruptedException
     */
    public FormValidation doSendTestMail(
        @QueryParameter String smtpServer,
        @QueryParameter String adminAddress,
        @QueryParameter boolean useSMTPAuth,
        @QueryParameter String smtpAuthUserName,
        @QueryParameter String smtpAuthPassword,
        @QueryParameter boolean useSsl,
        @QueryParameter String smtpPort)
        throws IOException, ServletException, InterruptedException {
      try {
        if (!useSMTPAuth) smtpAuthUserName = smtpAuthPassword = null;

        MimeMessage msg =
            new MimeMessage(
                createSession(
                    smtpServer,
                    smtpPort,
                    useSsl,
                    smtpAuthUserName,
                    Secret.fromString(smtpAuthPassword)));
        msg.setSubject("Test email #" + ++testEmailCount);
        msg.setContent(
            "This is test email #"
                + testEmailCount
                + " sent from Hudson Continuous Integration server.",
            "text/plain");
        msg.setFrom(new InternetAddress(adminAddress));
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(adminAddress));

        Transport.send(msg);

        return FormValidation.ok("Email was successfully sent");
      } catch (MessagingException e) {
        return FormValidation.errorWithMarkup(
            "<p>Failed to send out e-mail</p><pre>"
                + Util.escape(Functions.printThrowable(e))
                + "</pre>");
      }
    }
  private void postMail(String recipient, String subject, String message)
      throws MessagingException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.port", "" + 587);
    props.setProperty("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    Properties mailConf = readConf();

    MailAuthenticator ma =
        new MailAuthenticator(mailConf.getProperty("mail"), mailConf.getProperty("pw"));
    Session session = Session.getDefaultInstance(props, ma);
    MimeMessage msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress("from");
    msg.setFrom(addressFrom);
    InternetAddress addressTo = new InternetAddress(recipient, false);
    msg.setRecipient(Message.RecipientType.TO, addressTo);
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
  }
  @Test
  public void sendTextMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Properties properties = this.configuration.getAllProperties();
    assertEquals("true", properties.getProperty(DefaultMailSenderConfiguration.JAVAMAIL_SMTP_AUTH));
    Session session = Session.getInstance(properties, new XWikiAuthenticator(this.configuration));

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("*****@*****.**"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("mixed");
    // Add text in the body
    multipart.addBodyPart(
        this.defaultBodyPartFactory.create(
            "some text here", Collections.<String, Object>singletonMap("mimetype", "text/plain")));
    message.setContent(multipart);

    // Step 4: Send the mail
    this.sender.sendAsynchronously(Arrays.asList(message), session, null);

    // Verify that the mail has been received (wait maximum 10 seconds).
    this.mail.waitForIncomingEmail(10000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals(1, messages.length);
    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals("*****@*****.**", messages[0].getHeader("To", null));

    assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount());

    BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]);
    assertEquals("some text here", textBodyPart.getContent());
  }
Example #29
0
  public BaseMail(String account, String mailId, String... args) {
    _mailProp.put("mail.smtp.host", Config.EMAIL_SYS_HOST);
    _mailProp.put("mail.smtp.auth", Config.EMAIL_SYS_SMTP_AUTH);
    _mailProp.put("mail.smtp.port", Config.EMAIL_SYS_PORT);
    _mailProp.put("mail.smtp.socketFactory.port", Config.EMAIL_SYS_PORT);
    _mailProp.put("mail.smtp.socketFactory.class", Config.EMAIL_SYS_FACTORY);
    _mailProp.put("mail.smtp.socketFactory.fallback", Config.EMAIL_SYS_FACTORY_CALLBACK);

    _authenticator = Config.EMAIL_SYS_SMTP_AUTH ? new SmtpAuthenticator() : null;

    String mailAddr = getUserMail(account);

    if (mailAddr == null) return;

    MailContent content = MailSystem.getInstance().getMailContent(mailId);
    if (content == null) return;

    String message = compileHtml(account, content.getText(), args);

    Session mailSession = Session.getDefaultInstance(_mailProp, _authenticator);

    try {
      _messageMime = new MimeMessage(mailSession);
      _messageMime.setSubject(content.getSubject());
      try {
        _messageMime.setFrom(
            new InternetAddress(Config.EMAIL_SYS_ADDRESS, Config.EMAIL_SERVERINFO_NAME));
      } catch (UnsupportedEncodingException e) {
        _log.warning("Sender Address not Valid!");
      }
      _messageMime.setContent(message, "text/html");
      _messageMime.setRecipient(Message.RecipientType.TO, new InternetAddress(mailAddr));
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
Example #30
0
  /**
   * HTML 형식으로 된 메일을 보낸다.
   *
   * @param mailTo 받는사람 주소
   * @param mailFrom 보내는 사람 주소
   * @param subject 메일 제목
   * @param content HTML 메일 컨텐츠
   * @throws MessagingException
   * @throws UnsupportedEncodingException
   */
  public void sendHtmlMail(String mailTo, String mailFrom, String subject, String content)
      throws MessagingException, UnsupportedEncodingException {

    // properties object 얻기
    Properties props = System.getProperties();

    // SMTP host property 정의
    // props.put(smtpProps, smtpHost);
    props.put(SMTP_PROPS, SMTP_HOST);
    log.debug("[" + className + "]-SMTP_HOST =" + SMTP_HOST);

    // javax mail 을 디버깅 모드로 설정
    props.put(SMTP_DEBUG, SMTP_TRUE);
    log.debug("[" + className + "]-SMTP_TRUE =" + SMTP_TRUE);

    if (MarConstants.getServerName() == MarConstants.SERVER_LOCAL) {
      // gmail smtp 서비스 포트 설정
      props.put(SMTP_PORT, SMTP_PORTV2);
      props.put("type", "javax.mail.Session"); // 해도 그만 안해도 그만
      props.put("auth", "Application"); // 해도 그만 안해도 그만
      log.debug("[" + className + "]-SMTP_PORTV2 =" + SMTP_PORTV2);

      // 로그인할때 Transport Layer Security (TLS) 를 사용할것인지 설정 gmail 에선 tls가 필수가 아니므로 해도그만 안해도 그만이다.
      props.put(SMTP_TLS, SMTP_TRUE);
      props.put(SMTP_TRANS, SMTP_PROTOCOL); // 프로토콜 설정
      log.debug("[" + className + "]-filename =" + SMTP_TRUE);
      log.debug("[" + className + "]-filename =" + SMTP_PROTOCOL);

      // gmail 인증용  Secure Sockets Layer (SSL) 설정
      // gmail 에서 인증? 사용해주므로 요건 안해주면 안됨
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

    } else {
      props.put(SMTP_PORT, SMTP_PORTV);
      log.debug("[" + className + "]-filename =" + SMTP_PORTV);
    }

    // session 얻기
    Session session = null;

    if (MarConstants.getServerName() == MarConstants.SERVER_LOCAL) {
      // smtp 인증 을 설정
      props.put("mail.smtp.auth", "true");

      Authenticator auth =
          new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
              // return new PasswordAuthentication("*****@*****.**", "vlffldzm2102");
              return new PasswordAuthentication("*****@*****.**", "");
            }
          };
      // session 얻기
      session = Session.getDefaultInstance(props, auth);
      // log.debug("["+className+"]-session ="+session);
    } else {
      session = Session.getDefaultInstance(props, null);
      // log.debug("["+className+"]-session ="+session);
    }

    if (log.isDebugEnabled()) {
      session.setDebug(true);
    }

    log.debug("[" + className + "]-mailFrom =" + mailFrom);
    log.debug("[" + className + "]-mailTo =" + mailTo);

    // 새로운 message object 생성
    MimeMessage message = new MimeMessage(session);
    // MimeUtility.encodeText(subject, "KSC5601", "B");
    message.setHeader("Content-Type", "text/html; charset=" + MAIL_ENCODING);
    message.setHeader("Content-Transfer-Encoding", MAIL_ENCODING64);
    message.setSubject(subject);
    // 일반적인 message object 채우기
    // message.setContent(content, "text/html; charset=" + MAIL_ENCODING);
    // message.setContent(content, "text/html; charset=UTF-8");
    message.setContent(content, "text/html;charset=UTF-8");
    message.setFrom(new InternetAddress(mailFrom));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
    // message 보내기

    Transport.send(message);
    log.debug("[" + className + "]-Send Mail Success");
  }