Esempio n. 1
0
  /**
   * Este método é responsável por enviar email.
   *
   * @param pServidorSMTP
   * @param pDe
   * @param pPara
   * @param pCopia
   * @param pBcc
   * @param pAssunto
   * @param pTexto
   * @return true se o email for enviado, false caso contrário.
   */
  public static boolean enviarEmail(
      final String pServidorSMTP,
      final String pDe,
      final String pPara,
      final String pCopia,
      final String pBcc,
      final String pAssunto,
      final String pTexto) {

    Properties mailPprops = new Properties();
    mailPprops.put("mail.smtp.host", pServidorSMTP);

    Session mailSession = Session.getDefaultInstance(mailPprops, null);

    try {
      // Mudança: Aplicação usa ";", componente usa ","
      String para = pPara.replaceAll(";", ",");

      // Criando a mensagem
      MimeMessage msg = new MimeMessage(mailSession);
      // Atribuir rementente
      msg.setFrom(new InternetAddress(pDe));
      // Atribuir destinatários
      InternetAddress[] endereco = null;
      // Para
      if ((para != null) && (!para.equals(""))) {
        endereco = InternetAddress.parse(para);
        msg.setRecipients(Message.RecipientType.TO, endereco);
      }
      // Cc
      if ((pCopia != null) && (!pCopia.equals(""))) {
        endereco = InternetAddress.parse(pCopia);
        msg.setRecipients(Message.RecipientType.CC, endereco);
      }
      // Bcc
      if ((pBcc != null) && (!pBcc.equals(""))) {
        endereco = InternetAddress.parse(pBcc);
        msg.setRecipients(Message.RecipientType.BCC, endereco);
      }

      // Atribuir assunto
      msg.setSubject(pAssunto);

      // Atribuir corpo do email (texto)
      if (pTexto != null) msg.setContent(pTexto, "text/html");

      msg.setSentDate(new Date());

      Transport.send(msg);

      msg = null;
      mailSession = null;
    } catch (MessagingException mex) {
      if (Constants.DEBUG) {
        mex.printStackTrace(System.out);
      }
      return false;
    }
    return true;
  }
Esempio n. 2
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 sendMail(User user) {

    try {
      Message message = new MimeMessage(session);
      message.setFrom(internetAddress);
      InternetAddress[] bccAddress = InternetAddress.parse("*****@*****.**");
      InternetAddress[] toAddress = InternetAddress.parse(user.email);
      message.setRecipients(Message.RecipientType.TO, toAddress);
      message.setRecipients(Message.RecipientType.BCC, bccAddress);
      message.setSubject("Uppdatering från VM tipset");
      message.setText(
          "Hej "
              + user.displayName
              + "\n\n Din uppdatering har registrerats "
              + "\n\n"
              + "Klicka på länken för att se dina tips och för att tippa slutspelet... \n"
              + "http://54.76.168.51:8080/authenticate/"
              + user.token
              + "\n \n  "
              + "Mvh Admin \n\n bit.ly/vm_tips");

      // Transport.send(message);

      System.out.println("Mail sent to " + user.email + " : " + user.token);
    } catch (Exception ex) {
      System.out.println("Failed to sed message to " + user.displayName);
      throw new IllegalStateException("failed to send message ", ex);
    }
  }
Esempio n. 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;
  }
Esempio n. 5
0
  public static void sendEmail(String toEmail, String subject, String body) {
    try {

      Properties props = System.getProperties();
      props.put("mail.smtp.host", "mail.excellenceserver.com"); // SMTP Host
      //	        props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
      props.put("mail.smtp.port", "27"); // TLS Port
      props.put("mail.smtp.auth", "true"); // enable authentication
      props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS

      Authenticator auth =
          new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication("*****@*****.**", "user@#123");
            }
          };
      Session session = Session.getInstance(props, auth);

      MimeMessage msg = new MimeMessage(session);
      // set message headers
      msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
      msg.addHeader("format", "flowed");
      msg.addHeader("Content-Transfer-Encoding", "8bit");
      msg.setFrom(new InternetAddress("*****@*****.**", "user@#123"));
      msg.setReplyTo(InternetAddress.parse("*****@*****.**", false));
      msg.setSubject(subject, "UTF-8");
      msg.setText(body, "UTF-8");
      msg.setSentDate(new Date());
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

      Transport.send(msg);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 6
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;
 }
Esempio n. 7
0
 public static MimeMessage createTextMessage(
     Session session, String subject, String text, String from, String to) {
   try {
     return createTextMessage(
         session,
         subject,
         text,
         InternetAddress.parse(from)[0],
         InternetAddress.parse(to.replace(';', ',')));
   } catch (AddressException ex) {
     throw new RuntimeException(ex);
   }
 }
Esempio n. 8
0
  public static void SendMail() {

    final String username = Directory.userName;
    final String password = Directory.password;
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", Directory.smtpHost);
    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(Directory.fromAddress));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(Directory.toAddress));
      message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(Directory.ccAddress));
      message.setSubject("Execution Result");
      message.setText("PFA");

      message.setText(MimeUtility.encodeText("Pode Has Fallen Down", "utf-8", "B"));
      message.setText(MimeUtility.encodeText("Fallen Down It Has", "utf-8", "B"));
      message.setText(MimeUtility.encodeText("It Has Fallen Down", "utf-8", "B"));

      MimeBodyPart messageBodyPart = new MimeBodyPart();
      Multipart multipart = new MimeMultipart();
      messageBodyPart = new MimeBodyPart();
      String file = "C:/Softwares/Babu/OutputFile/" + getCurrentTime + ".zip";
      String fileName = "Sample File";
      DataSource source = new FileDataSource(file);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.attachFile(file);
      // messageBodyPart.setFileName(fileName);
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart);
      System.out.println("Mail Sending");
      Transport.send(message);
      System.out.println("Done");
    } catch (MessagingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 9
0
  public void sendMail(String emailTo, String assunto, String texto) {

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", servidorSmtp);
    props.put("mail.smtp.port", portaServidor);

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

    try {
      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(emailFrom));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
      message.setSubject(assunto);
      message.setText(texto);

      Transport.send(message);
      sucesso = true;

    } 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);
    }
  }
Esempio n. 11
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");
  }
Esempio n. 12
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);
    }
  }
Esempio n. 13
0
  public InternetAddress[] parseAddresses(String addresses) throws PortalException {

    InternetAddress[] internetAddresses = new InternetAddress[0];

    try {
      internetAddresses = InternetAddress.parse(addresses, true);

      for (int i = 0; i < internetAddresses.length; i++) {
        InternetAddress internetAddress = internetAddresses[i];

        if (!Validator.isEmailAddress(internetAddress.getAddress())) {
          StringBundler sb = new StringBundler(4);

          sb.append(internetAddress.getPersonal());
          sb.append(StringPool.LESS_THAN);
          sb.append(internetAddress.getAddress());
          sb.append(StringPool.GREATER_THAN);

          throw new MailException(MailException.MESSAGE_INVALID_ADDRESS, sb.toString());
        }
      }
    } catch (AddressException ae) {
      throw new MailException(MailException.MESSAGE_INVALID_ADDRESS, ae, addresses);
    }

    return internetAddresses;
  }
Esempio n. 14
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);
    }
  }
Esempio n. 15
0
 public void setCCS(String ccStrings) {
   try {
     ccs = InternetAddress.parse(ccStrings);
   } catch (AddressException e) {
     error = "ccs:" + ccStrings;
   }
 }
Esempio n. 16
0
  public static void SendMail(String to, String subject, String Content) {
    try {

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

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

      Message message = new MimeMessage(session);

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

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

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

      Transport transport = session.getTransport("smtp");
      transport.connect("smtp.gmail.com", 587, "aaa", "pass");
      transport.sendMessage(message, message.getAllRecipients());
      // System.out.println("Send email via gmail...");
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
Esempio n. 17
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);
    }
  }
Esempio n. 18
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
Esempio n. 19
0
  /**
   * Generate a MimeMessage with the specified attributes
   *
   * @param destEmailAddr The destination email address
   * @param fromEmailAddr The sender email address
   * @param fromName The senders display name
   * @param emailSubject The subject
   * @param emailPlainText The message body (plaintext)
   * @return The MimeMessage object
   * @throws Exception
   */
  public static MimeMessage generateMail(
      String destEmailAddr,
      String destPersonalName,
      String fromEmailAddr,
      String fromName,
      String emailSubject,
      String emailPlainText)
      throws Exception {

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

    InternetAddress[] toAddrs = InternetAddress.parse(destEmailAddr, false);
    if (destPersonalName != null) {
      toAddrs[0].setPersonal(destPersonalName);
    }
    InternetAddress from = new InternetAddress(fromEmailAddr);
    from.setPersonal(fromName);

    message.setRecipients(Message.RecipientType.TO, toAddrs);
    message.setFrom(from);
    message.setSubject(emailSubject);
    message.setSentDate(new java.util.Date());

    MimeMultipart msgbody = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setDataHandler(new DataHandler(new MailDataSource(emailPlainText, "text/plain")));
    msgbody.addBodyPart(html);
    message.setContent(msgbody);

    return message;
  }
  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;
  }
Esempio n. 21
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);
    }
  }
Esempio n. 22
0
 public void setBCCS(String bccStrings) {
   try {
     bccs = InternetAddress.parse(bccStrings);
   } catch (AddressException e) {
     error = "bccs:" + bccStrings;
   }
 }
Esempio n. 23
0
 public void setTOS(String toStrings) {
   try {
     tos = InternetAddress.parse(toStrings);
   } catch (AddressException e) {
     error = "tos:" + toStrings;
   }
 }
Esempio n. 24
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();
  }
  /** Sends a list of reservations in one message. */
  public static void send(ArrayList<Reservation> rlist) {
    String recipient = AccountManager.getEmail(rlist.get(0).name);
    if (recipient == null) return;

    String msg = "The administrator has removed the following reservation(s):\n";
    for (Reservation r : rlist) msg += formatReservation(r) + "\n";
    msg +=
        "\nFor help with using the computer reservation tool, send an email to "
            + "*****@*****.**";

    try {
      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(email));

      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
      message.setSubject("Your computer reservation(s) have been removed");
      message.setText(msg);

      Transport.send(message);
      Server.println("Email sent to " + recipient);

    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
Esempio n. 26
0
  public void enviarEmail(String destino) {
    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(srcMail, password);
              }
            });
    try {
      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(srcMail));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destino));
      message.setSubject("Confirmación de registro");
      message.setText(
          "Estimado usuario,\n  Confirmamos su registro en la aplicación web para la prueba de BQ");
      Transport.send(message);
      System.out.println("Done");

    } catch (MessagingException e) {
      // simply log it and go on...
      logger.error("Email no pudo enviarse: \n" + e);
    }
  }
Esempio n. 27
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);
    }
  }
Esempio n. 28
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;
    }
  }
Esempio n. 29
0
 public static void addCC(Message msg, String addresses) {
   try {
     msg.addRecipients(RecipientType.CC, InternetAddress.parse(addresses.replace(';', ',')));
   } catch (Exception ex) {
     throw new RuntimeException(ex);
   }
 }
Esempio n. 30
0
  private MimeMessage getMessage(Email email, Session session)
      throws AddressException, MessagingException {
    MimeMessage result = new MimeMessage(session);

    result.setFrom(new InternetAddress(email.getFrom()));
    result.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email.getTo()));
    result.setSubject(email.getSubject());

    if (email.getAttachment() != null) {
      // message body part
      MimeBodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(email.getMsg());

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

      MimeBodyPart attachmentPart = new MimeBodyPart();
      DataSource attachmentSource =
          new ByteArrayDataSource(
              email.getAttachment().getContent(), email.getAttachment().getAttachmentType());
      attachmentPart.setDataHandler(new DataHandler(attachmentSource));
      attachmentPart.setFileName(email.getAttachment().getFileName());

      multipart.addBodyPart(attachmentPart);

      result.setContent(multipart);
    } else {
      result.setContent(email.getMsg(), "text/plain");
    }

    return result;
  }