Example #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); // 发送
  }
Example #2
0
  public static void sendConfirmationRegisterMail(String mail, String name)
      throws UnsupportedEncodingException, MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session =
        Session.getDefaultInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
              }
            });

    String msgBody = "The staff wish you enjoy the contest!";

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(FROM_ADDRESS, FROM_NAME));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, name));
    msg.setSubject("Welcome to pContest!");
    msg.setText(msgBody);
    Transport.send(msg);
  }
Example #3
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;
  }
Example #4
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;
  }
Example #5
0
  public boolean send() {

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
      fromAddress = new InternetAddress(from);
      toAddress = new InternetAddress(to);
    } catch (AddressException e) {
      e.printStackTrace();
      return false;
    }

    try {
      simpleMessage.setFrom(fromAddress);
      simpleMessage.setRecipient(RecipientType.TO, toAddress);
      simpleMessage.setSubject(subject);
      simpleMessage.setText(text);

      Transport.send(simpleMessage);
      return true;
    } catch (MessagingException e) {
      e.printStackTrace();
      return false;
    }
  }
Example #6
0
  public void send(String subject, String text, String fromEmail, String toEmail) {
    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
              }
            });

    try {
      Message message = new MimeMessage(session);
      // от кого
      message.setFrom(new InternetAddress(username));
      // кому
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
      // тема сообщения
      message.setSubject(subject);
      // текст
      message.setText(text);

      // отправляем сообщение
      Transport.send(message);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
  public void sendEmail(String email, String password) {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", false);
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", 587);
    Session session =
        Session.getInstance(
            properties,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("*****@*****.**", "test123");
              }
            });

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress("*****@*****.**"));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
      message.setSubject("Reset Password");
      String content = "Your new password is " + password;
      message.setText(content);
      Transport.send(message);

    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
Example #8
0
  public void sendMail(String id, String mail) {
    System.out.println("In de send mail method");
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Beta-SMS user,\n Thank you for submiting a feature/issue request. You can follow the status at http://beta-sms.coralic.nl?TABTOSELECT=tab-todo&ID="
            + id
            + "\n \n Thank you for using Beta-SMS.";

    try {
      System.out.println("Building the email and trying to send it");
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "beta-sms.coralic.nl Beta-SMS"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, mail));
      msg.setSubject("Beta-SMS feature/issue request processed.");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (AddressException e) {
      System.err.println(e.getMessage());
    } catch (MessagingException e) {
      System.err.println(e.getMessage());
    } catch (UnsupportedEncodingException e) {
      System.err.println(e.getMessage());
    }
  }
 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();
   }
 }
  public static void sendEmail(String title, String message, String email)
      throws MessagingException {

    Properties props = new Properties();
    props.setProperty("mail.smtp.auth", "true"); // 设置访问smtp服务器需要认证
    props.setProperty("mail.transport.protocol", "smtp"); // 设置访问服务器的协议

    Session session = Session.getDefaultInstance(props);
    session.setDebug(true); // 打开debug功能

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(user)); // 设置发件人,163邮箱要求发件人与登录用户必须一致(必填),其它邮箱不了解
    msg.setText(message); // 设置邮件内容
    msg.setSubject("Test"); // 设置邮件主题

    Transport trans = session.getTransport();
    try {
      trans.connect("smtp.163.com", 25, user, pwd); // 连接邮箱smtp服务器,25为默认端口
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      trans.sendMessage(msg, new Address[] {new InternetAddress(email)}); // 发送邮件
    } catch (Exception e) {
      e.printStackTrace();
    }

    trans.close(); // 关闭连接
  }
Example #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);
     }
   }
 }
  public static boolean sendEmail(String email, String text, String subject) {
    final String username = "******";
    final String password = "******";
    try {
      Properties prop = new Properties();
      prop.put("mail.smtp.auth", "true");
      prop.put("mail.smtp.starttls.enable", "true");
      prop.put("mail.smtp.host", "smtp.gmail.com");
      prop.put("mail.smtp.port", "587");

      Session session =
          Session.getInstance(
              prop,
              new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(username, password);
                }
              });
      try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        msg.setSubject(subject);
        msg.setText(text);
        Transport.send(msg);
        return true;
      } catch (MessagingException me) {
        me.printStackTrace();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
Example #13
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String email = request.getParameter("email");

    Properties pros = System.getProperties();
    pros.setProperty("mail.smtp.host", "localhost");

    Session mailsession = Session.getDefaultInstance(properties);

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String to = email;
    String from = "*****@*****.**"; // enter the senders email
    String subject = ""; // enter a subject
    String body = "";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(from));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      msg.setSubject(subject);
      msg.setText(body);
      Transport.send(message);
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
Example #14
0
  public Boolean sendMail(String body, String recept) {

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

    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    Session session =
        Session.getInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
              }
            });

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress("*****@*****.**"));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recept));
      message.setSubject("*** This is an automatically generated email, please do not reply ***");
      message.setText(
          "Hi there,\n\nPlease find the information you need below:\n"
              + body
              + "\n\nThanks,\n-Kiran");
      Transport.send(message);
      return true;
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
Example #15
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);
  }
Example #16
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
  public static void main(String[] args) throws Exception {

    final Properties props = new Properties();
    props.load(ClassLoader.getSystemResourceAsStream("mail.properties"));

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

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(props.getProperty("address.sender")));
    message.setRecipient(
        Message.RecipientType.TO, new InternetAddress(props.getProperty("address.recipient")));
    message.setSubject("Test JavaMail");

    message.setText("Hello!\n\n\tThis is a test message from JavaMail.\n\nThank you.");

    Transport.send(message);

    log.info("Message was sent");
  }
Example #18
0
  public static void send(String msg) {
    final String fromEmail = "*****@*****.**";
    final String toEmail = "*****@*****.**";
    final String password = "";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Authenticator auth =
        new Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromEmail, password);
          }
        };

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

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(fromEmail));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
      message.setSubject("File Uploaded");
      message.setText(msg);

      Transport.send(message);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
Example #19
0
  public static void sendMail(String subject, String body) throws IOException, MessagingException {
    final Properties props = new Properties();
    // load a properties file
    props.load(new FileInputStream("mailer.properties"));

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

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(props.getProperty("user.email")));
    message.setRecipients(
        Message.RecipientType.TO, InternetAddress.parse(props.getProperty("user.email")));
    message.setSubject(subject);
    message.setText(body);

    Transport.send(message);

    System.out.println("mail sent");
  }
  // 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 {

    }
  }
  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);
  }
  public static void passwordResetLinkMail(String email) {
    System.out.println("in password reset link");
    System.out.println("email is " + email);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Employee"
            + "As your request we've sent you a password reset link\n"
            + "Past this link to address-bar or click on this link to reset your password\n"
            + "Link is [http://prodigy-software.appspot.com/passwordResetLink]"
            + "\n"
            + "Regards,\n"
            + "  HR  ";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "HR Manager"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Hi prodigy"));
      msg.setSubject("Password Reset Link");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (Exception e) {

    }
  }
Example #23
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());
    }
  }
  public static void leaveApprovedMail(
      String employeeName, String fromDate, String toDate, String email) {

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

    String msgBody =
        "Hi "
            + employeeName.toUpperCase()
            + "In response to your request for leave on date from "
            + fromDate
            + " to "
            + toDate
            + " \n"
            + "the management pleased to inform you that your leave request is approved.\n"
            + "Also, do delegate your daily work responsibilities to your assistants\n"
            + "and subordinates well to ensure a smooth flow of operation in your absence.\n"
            + "For your information, with these approved  days of leave,\n"
            + "We wish you a good rest on your off days.\n"
            + "Regards,\n"
            + "  HR  ";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "HR Manager"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, employeeName));
      msg.setSubject("Leave Request Approved");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (Exception e) {

    }
  }
 /**
  * 以文本格式发送邮件
  *
  * @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;
 }
  public static void leaveDeclinedMail(String email, String employeeId) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Employee"
            + "This letter is in response to your request for a leave of absence beginning"
            + " through   Although we make every effort"
            + " to accommodate employees with a need for time off, unfortunately,"
            + " your leave request is not approved due to Project deadLine to complete"
            + "If you feel that this decision is made in error or that extenuating circumstances warrant"
            + "further review of your request, please feel free to contact me with more information or"
            + "additional details surrounding your need for leave."
            + "Regards,\n"
            + "  HR  ";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "HR Manager"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Hi prodigy"));
      msg.setSubject("Leave Request Declined");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (Exception e) {

    }
  }
Example #27
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();
  }
  // 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();
  }
Example #29
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);
   }
 }
Example #30
0
  public static void sendMailTSL(String[] args) {

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

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

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(user));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("*****@*****.**"));
      message.setSubject("Testing Subject");
      message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!");

      Transport.send(message);

      System.out.println("Done");

    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }