Ejemplo n.º 1
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); // 发送
  }
Ejemplo n.º 2
0
  // Prefered way of how it should be used.
  public MailAgent(
      String to,
      String cc,
      String bcc,
      String from,
      String subject,
      String content,
      String smtpHost)
      throws FrameworkExecutionException {
    try {
      this.to = to;
      this.cc = cc;
      this.bcc = bcc;
      this.from = from;
      this.subject = subject;
      this.content = content;
      this.smtpHost = smtpHost;

      message = createMessage();
      message.setFrom(new InternetAddress(from));
      setToCcBccRecipients();

      message.setSentDate(new Date());
      message.setSubject(subject);
      message.setText(content);
    } catch (AddressException ex) {
      throw new FrameworkExecutionException(ex);
    } catch (MessagingException ex) {
      throw new FrameworkExecutionException(ex);
    } finally {

    }
  }
Ejemplo n.º 3
0
  // Send the specified message.
  public void sendMessage(int type, Message message) throws Exception {
    // Display message dialog to get message values.
    MessageDialog dialog;
    dialog = new MessageDialog(this, null, type, message);
    if (!dialog.display()) {
      // Return if dialog was cancelled.
      return;
    }

    // Create a new message with values from dialog.
    Message newMessage = new MimeMessage(session);
    newMessage.setFrom(new InternetAddress(dialog.getFrom()));

    newMessage.setSubject(dialog.getSubject());
    newMessage.setSentDate(new Date());
    newMessage.setText(dialog.getContent());

    final Address[] recipientAddresses = InternetAddress.parse(dialog.getTo());
    newMessage.setRecipients(Message.RecipientType.TO, recipientAddresses);

    Transport transport = session.getTransport("smtps");
    transport.connect(getSmtpServer(), GMAIL_SMTP_PORT, getUsername(), getPassword());
    transport.sendMessage(newMessage, recipientAddresses);
    transport.close();
  }
Ejemplo n.º 4
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");
  }
Ejemplo n.º 5
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;
    }
  }
Ejemplo n.º 6
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;
  }
Ejemplo n.º 7
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();
  }
Ejemplo n.º 8
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);
   }
 }
Ejemplo n.º 9
0
 /**
  * 以文本格式发送邮件
  *
  * @param mailInfo 待发送的邮件信息
  */
 public static boolean sendTextMail(MailSenderInfo mailInfo) {
   // 判断是否需要身份认证
   MailAuthenticator authenticator = null;
   Properties pro = mailInfo.getProperties();
   if (mailInfo.isValidate()) {
     // 如果需要身份认证,则创建一个密码验证器
     authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
   }
   // 根据邮件会话属性和密码验证器构造一个发送邮件的session
   Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
   try {
     // 根据session创建一个邮件消息
     Message mailMessage = new MimeMessage(sendMailSession);
     // 创建邮件发送者地址
     Address from = new InternetAddress(mailInfo.getFromAddress());
     // 设置邮件消息的发送者
     mailMessage.setFrom(from);
     // 创建邮件的接收者地址,并设置到邮件消息中
     Address to = new InternetAddress(mailInfo.getToAddress());
     mailMessage.setRecipient(Message.RecipientType.TO, to);
     // 设置邮件消息的主题
     mailMessage.setSubject(mailInfo.getSubject());
     // 设置邮件消息发送的时间
     mailMessage.setSentDate(new Date());
     // 设置邮件消息的主要内容
     String mailContent = mailInfo.getContent();
     mailMessage.setText(mailContent);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
Ejemplo n.º 10
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();
  }
Ejemplo n.º 11
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();
  }
Ejemplo n.º 12
0
  public static void main(String[] args) {
    SiteCycler SiteCycler = new SiteCycler();
    // to do
    // set it so that it gets the headers of "http://www." + Vars.site and sertches that string for
    // apachie then for a string
    // like 2.2.15

    try {

      Properties props = new Properties();
      props.put("mail.smtp.host", "smtp.gmail.com"); // for gmail use smtp.gmail.com
      props.put("mail.smtp.auth", "true");
      props.put("mail.debug", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.port", "465");
      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 mailSession =
          Session.getInstance(
              props,
              new javax.mail.Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication("email", "password");
                }
              });

      mailSession.setDebug(true); // Enable the debug mode

      Message msg = new MimeMessage(mailSession);
      String http = "http://www.";
      // --[ Set the FROM, TO, DATE and SUBJECT fields
      msg.setFrom(new InternetAddress("*****@*****.**"));
      msg.setRecipients(
          Message.RecipientType.TO,
          InternetAddress.parse(
              "nick.m.mckenna@" + Vars.site)); // "admin@"+site+ // this is the part that sets the
      // [email protected]
      msg.setSentDate(new Date());
      msg.setSubject("Hello World!");

      // --[ Create the body of the mail
      SiteCycler sitecycler = new SiteCycler();
      msg.setText(
          "Hello I am assumeing that you are the admin of "
              + Vars.site
              + " I am nick a Whitehat Hacker etc etc etc etc stuff memory words time things");

      // --[ Ask the Transport class to send our mail message
      Transport.send(msg);

    } catch (Exception E) {
      System.out.println("Oops!");
      System.out.println(E);
    }
  }
Ejemplo n.º 13
0
 /* (non-Javadoc)
  * @see se.hiq.hicollege.core.mail.EmailService#sendEmail(se.hiq.hicollege.core.mail.MailForm)
  */
 @Override
 public void sendEmail(MailForm mailForm) throws MessagingException {
   logger.debug("Started sendEmail");
   Message message = mailForm.getMessage(mailSession);
   Date timeStamp = new Date();
   message.setSentDate(timeStamp);
   Transport.send(message);
   logger.debug("Message sent at: " + timeStamp);
 }
Ejemplo n.º 14
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();
      }
    }
  }
Ejemplo n.º 15
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);
  }
Ejemplo n.º 16
0
 protected Message getFullyLoad(Message message, Folder folder, String context)
     throws MessagingException {
   try {
     ((GoogleVoiceFolder) folder).loadFully((GoogleVoiceMessage) message);
   } catch (Exception e) {
     throw new MessagingException("Exception getting googlevoice message body " + e.getMessage());
   }
   Message wrappedMessage = new MimeMessage((MimeMessage) message);
   wrappedMessage.setSentDate(message.getSentDate());
   return wrappedMessage;
 }
Ejemplo n.º 17
0
 private static Message createSMTPMessage(
     Session session, String from, String to, String subject, String body)
     throws MessagingException {
   Message msg = new MimeMessage(session);
   msg.setFrom(new InternetAddress(from));
   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
   msg.setSentDate(new Date());
   msg.setSubject(subject);
   msg.setHeader("X-Mailer", "Java Mail API");
   msg.setText(body);
   return msg;
 }
Ejemplo n.º 18
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;
 }
Ejemplo n.º 19
0
  public void send(EmailBuilder[] emails, SmtpConfig smtp)
      throws AddressException, MessagingException, IOException {
    Properties props = System.getProperties();
    if (smtp.getHost() != null) {
      props.put("mail.smtp.host", smtp.getHost());
    }
    if (smtp.isAuth()) {
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtps.auth", "true");
    }
    if (smtp.isStarttls()) {
      props.put("mail.smtp.starttls.enable", "true");
    }
    // Get a Session object
    Session session = Session.getInstance(props, null);
    if (debug) {
      session.setDebug(true);
    }

    SMTPTransport transport = null;
    try {
      for (EmailBuilder email : emails) {
        // construct the message
        Message msg = email.getMessage(email, session);
        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        if (transport == null) {
          transport = (SMTPTransport) session.getTransport(smtp.isSsl() ? "smtps" : "smtp");
          if (smtp.isAuth()) {
            transport.connect(smtp.getHost(), smtp.getUser(), smtp.getPassword());
          } else {
            transport.connect();
          }
        }
        try {
          transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
          if (verbose) {
            System.out.println("SmtpMailer: Response = " + transport.getLastServerResponse());
          }
        }
        if (verbose) {
          System.out.println("SmtpMailer: E-Mail successfully sent.");
        }
      }
    } finally {
      if (transport != null) transport.close();
    }
  }
Ejemplo n.º 20
0
  public static boolean SendMail(
      String from, String to, String cc, String subject, String content) {
    Properties props = System.getProperties();
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");

    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.failBack", "false");
    props.put("mail.smtp.quitwait", "false");

    try {
      Session session =
          Session.getInstance(
              props,
              new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication("*****@*****.**", "3003191114");
                }
              });
      Message message = new MimeMessage(session);
      Address fromAdd = new InternetAddress(to);
      Address toAdd = new InternetAddress(to);
      Address ccAdd = new InternetAddress(cc);

      message.setFrom(fromAdd);
      message.setRecipient(Message.RecipientType.TO, toAdd);
      message.setRecipient(Message.RecipientType.CC, ccAdd);

      MimeBodyPart messagePart = new MimeBodyPart();
      MimeMultipart mutilPart = new MimeMultipart();

      mutilPart.addBodyPart(messagePart);

      messagePart.setText(content, "utf-8");
      messagePart.setHeader("Content-Type", "text/html;character=\"utf-8\"");
      messagePart.setHeader("Content-Transfer-Encoding", "quoted-printable");

      message.setSubject(subject);
      message.setContent(mutilPart);
      message.setSentDate(new Date());

      Transport.send(message);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
Ejemplo n.º 21
0
  public void sendEmailWithAttachment() throws AddressException, MessagingException {
    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", getHostName());
    properties.put("mail.smtp.port", getPort());
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.user", getFrom());
    properties.put("mail.password", getPassword());

    // creates a new session with an authenticator
    Authenticator auth =
        new Authenticator() {
          public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(getFrom(), getPassword());
          }
        };
    Session session = Session.getInstance(properties, auth);

    // creates a new e-mail message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(getFrom()));
    InternetAddress[] toAddresses = {new InternetAddress(getTo())};
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(getSubject());
    msg.setText(getMessage());
    msg.setSentDate(new Date());

    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(getMessage(), "text/html");

    // creates multi-part
    Multipart multipart = new MimeMultipart();

    DataSource source = new FileDataSource(getFile());
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(getFile());

    multipart.addBodyPart(messageBodyPart);

    // Send the complete message parts
    msg.setContent(multipart);

    // sends the e-mail
    Transport.send(msg);
  }
  protected void sendNotif(ICNotification notif, Object target) throws Exception {
    // Creating message
    Message s_message = new MimeMessage(session);

    // Set message properties
    s_message.setFrom(new InternetAddress(sender));
    s_message.setSubject(notif.getAttrib(NOTIF_SUBJECT));
    s_message.setText(notif.getAttrib(NOTIF_CONTENT));
    s_message.setSentDate(new Date(notif.getTimeMsec()));

    for (Iterator it = ((Set) target).iterator(); it.hasNext(); ) {
      s_message.addRecipient(Message.RecipientType.TO, new InternetAddress((String) it.next()));
    }
    // Sending message
    transport.sendMessage(s_message, s_message.getAllRecipients());
  }
Ejemplo n.º 23
0
 /**
  * 以文本格式发送邮件
  *
  * @param entity 待发送的邮件的信息
  */
 public boolean sendTextMail(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(entity.getToAddress());
     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());
     // 设置邮件消息的主要内容
     String mailContent = entity.getContent();
     mailMessage.setText(mailContent);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
Ejemplo n.º 24
0
 /**
  * 以HTML格式发送邮件
  *
  * @param mailInfo 待发送的邮件信息
  */
 public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
   // 判断是否需要身份认证
   MyAuthenticator authenticator = null;
   Properties pro = mailInfo.getProperties();
   // 如果需要身份认证,则创建一个密码验证器
   if (mailInfo.isValidate()) {
     authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
   }
   // 根据邮件会话属性和密码验证器构造一个发送邮件的session
   Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
   try {
     // 根据session创建一个邮件消息
     Message mailMessage = new MimeMessage(sendMailSession);
     // 创建邮件发送者地址
     Address from = new InternetAddress(mailInfo.getFromAddress());
     // 设置邮件消息的发送者
     mailMessage.setFrom(from);
     // 创建邮件的接收者地址,并设置到邮件消息中
     Address to = new InternetAddress(mailInfo.getToAddress());
     // Message.RecipientType.TO属性表示接收者的类型为TO
     mailMessage.setRecipient(Message.RecipientType.TO, to);
     // 设置邮件消息的主题
     mailMessage.setSubject(mailInfo.getSubject());
     // 设置邮件消息发送的时间
     mailMessage.setSentDate(new Date());
     // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
     Multipart mainPart = new MimeMultipart();
     // 创建一个包含HTML内容的MimeBodyPart
     BodyPart html = new MimeBodyPart();
     // 设置HTML内容
     html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
     mainPart.addBodyPart(html);
     // 将MiniMultipart对象设置为邮件内容
     mailMessage.setContent(mainPart);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
Ejemplo n.º 25
0
 @Override
 public Mail send(Mail mail, MailContext ctx) {
   try {
     Session session = ctx.getSession();
     Message mailMessage = new MimeMessage(session);
     // 设置发件人地址
     Address from = new InternetAddress(ctx.getUser() + " <" + ctx.getAccount() + ">");
     mailMessage.setFrom(from);
     // 设置所有收件人的地址
     Address[] to = getAddress(mail.getReceivers());
     mailMessage.setRecipients(Message.RecipientType.TO, to);
     // 设置抄送人地址
     Address[] cc = getAddress(mail.getCcs());
     mailMessage.setRecipients(Message.RecipientType.CC, cc);
     // 设置主题
     mailMessage.setSubject(mail.getSubject());
     // 发送日期
     mailMessage.setSentDate(new Date());
     // 构建整封邮件的容器
     Multipart main = new MimeMultipart();
     // 正文的body
     BodyPart body = new MimeBodyPart();
     body.setContent(mail.getContent(), "text/html; charset=utf-8");
     main.addBodyPart(body);
     // 处理附件
     for (FileObject f : mail.getFiles()) {
       // 每个附件的body
       MimeBodyPart fileBody = new MimeBodyPart();
       fileBody.attachFile(f.getFile());
       // 为文件名进行转码
       fileBody.setFileName(MimeUtility.encodeText(f.getSourceName()));
       main.addBodyPart(fileBody);
     }
     // 将正文的Multipart对象设入Message中
     mailMessage.setContent(main);
     Transport.send(mailMessage);
     return mail;
   } catch (Exception e) {
     e.printStackTrace();
     throw new SendMailException("发送邮件错误, 请检查邮箱配置及邮件的相关信息");
   }
 }
Ejemplo n.º 26
0
  public void sendEmail(String fromAddress, List<String> toAddress, String subject, String body)
      throws MessagingException {
    Properties props = new Properties();
    props.setProperty("mail.transport.protocol", "smtp");
    props.put("mail.host", _mailHost);
    props.put("mail.user", _mailUser);
    props.put("mail.password", _mailPassword);

    Session session = Session.getDefaultInstance(props);
    Message message = new MimeMessage(session);
    InternetAddress from =
        new InternetAddress(fromAddress == null ? "*****@*****.**" : fromAddress, false);
    message.setFrom(from);
    for (String toAddr : toAddress)
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddr, false));
    message.setSubject(subject);
    message.setText(body);
    message.setSentDate(new Date());
    Transport.send(message);
  }
Ejemplo n.º 27
0
  /**
   * @param logEntry Log entry
   * @param repositoryName Name
   * @param mailTemplate Template
   * @return Message
   * @throws MessagingException If a message exception occurs.
   * @throws IOException if a IO exception occurs while creating the data source.
   */
  private Message createMessage(
      final SVNLogEntry logEntry, RepositoryName repositoryName, String mailTemplate)
      throws MessagingException, IOException {
    final Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(
        Message.RecipientType.BCC, receivers.toArray(new InternetAddress[receivers.size()]));
    msg.setSubject(formatSubject(subject, logEntry.getRevision(), repositoryName));

    msg.setDataHandler(
        new DataHandler(
            new ByteArrayDataSource(
                HTMLCreator.createRevisionDetailBody(
                    mailTemplate, logEntry, baseUrl, repositoryName, dateFormat, null),
                "text/html")));

    msg.setHeader("X-Mailer", "sventon");
    msg.setSentDate(new Date());
    return msg;
  }
Ejemplo n.º 28
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;
    }
  }
  public void sendEmail(
      String host,
      String port,
      String userName,
      String password,
      String toAddress,
      String subject,
      String message)
      throws MessagingException {
    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");

    // creates a new session with an authenticator
    Authenticator auth =
        new Authenticator() {
          public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
          }
        };

    Session session = Session.getInstance(properties, auth);

    // creates a new e-mail message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = {new InternetAddress(toAddress)};
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setText(message);

    // sends the e-mail
    Transport.send(msg);
  }
Ejemplo n.º 30
0
  public String sendMail(String message, String reciver) {
    String stamp = null;
    try {
      Message mailMessage = new MimeMessage(mailSession);
      mailMessage.setFrom(new InternetAddress(sender));
      mailMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(reciver, false));
      mailMessage.setSubject(subject);
      mailMessage.setText(message);

      Date date = new Date();
      mailMessage.setSentDate(date);

      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm:ss");
      stamp = dateFormat.format(date);

      Transport.send(mailMessage);
    } catch (Throwable e) {
      if (e.toString().contains("SendFailedException")) return sendMail(message);
      stamp = e.toString();
    }
    return stamp;
  }