private void sendNewItems(String[][] itemsMatrix, Date firstDate, Date lastDate) {
    Multipart multipart = new MimeMultipart();

    Writer writer = generateCSV(itemsMatrix);

    Session session = getSession();
    String from = getFromAddress();

    Set<String> recipients = getRecipients();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    String firstDateStr = sdf.format(firstDate);
    String lastDateStr = sdf.format(lastDate);

    List<String> arguments = new ArrayList<String>();
    arguments.add(firstDateStr);
    arguments.add(lastDateStr);

    String messageText =
        "Please find attached the items that have been created in Digital Collections.";
    try {
      messageText = getMessageText("mail/newmail.txt", arguments.toArray(new String[0]));
    } catch (IOException e) {
      // Do nothing instead use default text;
    }
    try {
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      for (String to : recipients) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      }
      message.setSubject("New items in Digital Collections list");

      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(messageText);
      multipart.addBodyPart(messageBodyPart);

      messageBodyPart = new MimeBodyPart();
      messageBodyPart.setFileName("new_dspace_items.csv");
      messageBodyPart.setText(writer.toString());

      multipart.addBodyPart(messageBodyPart);

      message.setContent(multipart);
      Transport.send(message);
      LOGGER.info("Sent message successfully...");
    } catch (MessagingException e) {
      LOGGER.error("Error sending message", e);
    }
  }
Beispiel #2
0
 public boolean send() throws Exception {
   Properties props = _setProperties();
   if (!_user.equals("")
       && !_pass.equals("")
       && _to.length > 0
       && !_from.equals("")
       && !_subject.equals("")
       && !_body.equals("")) {
     Session session = Session.getInstance(props, this);
     MimeMessage msg = new MimeMessage(session);
     msg.setFrom(new InternetAddress(_from));
     InternetAddress[] addressTo = new InternetAddress[_to.length];
     for (int i = 0; i < _to.length; i++) {
       addressTo[i] = new InternetAddress(_to[i]);
     }
     msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
     msg.setSubject(_subject);
     msg.setSentDate(new Date()); // setup message body
     BodyPart messageBodyPart = new MimeBodyPart();
     messageBodyPart.setText(_body);
     _multipart.addBodyPart(messageBodyPart); // Put parts in message
     msg.setContent(_multipart); // send email
     Transport.send(msg);
     return true;
   } else {
     return false;
   }
 }
Beispiel #3
0
    public void send(final Email email) throws MessagingException {
      if (email.getMessage().getSender().getFromName() == null) {
        logProblem("error.from.address.cannot.be.null");
        abort();
        return;
      }

      final String from =
          constructFromString(
              encode(email.getMessage().getFromName()), email.getMessage().getFromAddress());

      final String[] replyTos = email.replyTos();
      final Address[] replyToAddresses = new Address[replyTos == null ? 0 : replyTos.length];
      if (replyTos != null) {
        for (int i = 0; i < replyTos.length; i++) {
          try {
            replyToAddresses[i] = new InternetAddress(encode(replyTos[i]));
          } catch (final AddressException e) {
            logProblem("invalid.reply.to.address: " + replyTos[i]);
            abort();
            return;
          }
        }
      }

      setFrom(new InternetAddress(from));
      setSubject(encode(email.getSubject()));
      setReplyTo(replyToAddresses);

      final String body = email.getBody();
      final String htmlBody = getHtmlBody();

      final MimeMultipart mimeMultipart = createMimeMultipart(body, htmlBody);

      if (body != null && !body.trim().isEmpty()) {
        final BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(body);
        mimeMultipart.addBodyPart(bodyPart);
      }

      if (htmlBody != null && !htmlBody.trim().isEmpty()) {
        final BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent(htmlBody, "text/html; charset=utf-8");
        mimeMultipart.addBodyPart(bodyPart);
      }

      setContent(mimeMultipart);

      addRecipientsAux();

      LOG.info("Sending email {} with message id {}", email.getExternalId(), getMessageID());

      Transport.send(this);

      final Address[] allRecipients = getAllRecipients();
      setConfirmedAddresses(allRecipients);
    }
Beispiel #4
0
  protected void sendFile() throws Exception {

    System.out.println("send file yaar");
    Properties props = new Properties();
    Session session = Session.getInstance(props, null);

    message123 = new MimeMessage(session);

    try {
      message123.setFrom(new InternetAddress(username.getText()));
    } catch (AddressException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    message123.setRecipients(Message.RecipientType.TO, emailID.getText());

    message123.setSubject("JavaMail Attachment");

    BodyPart messageBodyPart = new MimeBodyPart();

    messageBodyPart.setText("Here's the file");

    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();

    DataSource source = new FileDataSource(str);

    messageBodyPart.setDataHandler(new DataHandler(source));

    messageBodyPart.setFileName(str);

    multipart.addBodyPart(messageBodyPart);

    message123.setContent(multipart);

    /*       try {
        Transport tr = session.getTransport("smtps");
        tr.connect(SMTP_HOST_NAME, username.getText(), password.getText());
        tr.sendMessage(message123, message123.getAllRecipients());
        System.out.println("Mail Sent Successfully");
        tr.close();

    } catch (SendFailedException sfe) {

        System.out.println(sfe);
    }*/
  }
  /**
   * @param MostrarInforme Abre una ventana con el informe del email
   * @param SERVIDOR
   * @param PUERTO
   */
  public boolean sendMailHTML(boolean MostrarInforme, String SERVIDOR, String PUERTO) {
    if (MostrarInforme) {
      Informe.setVisible(true);
      Informe.setAlwaysOnTop(true);
    }
    try {
      Informe.setTitulo("Destino: " + Destinatarios.get(0));
      Properties props = new Properties();
      props.put("mail.smtp.host", SERVIDOR); // "wo06.wiroos.com" o "smtp.gmail.com"
      props.setProperty("mail.smtp.starttls.enable", "true");
      //          props.setProperty("mail.smtp.port", "587");
      props.setProperty("mail.smtp.port", PUERTO); // "587");
      props.setProperty("mail.smtp.user", usuarioCorreo);
      props.setProperty("mail.smtp.auth", "true");

      Session session = Session.getDefaultInstance(props, null);
      BodyPart texto = new MimeBodyPart();
      texto.setText(mensaje);

      BodyPart adjunto = new MimeBodyPart();
      if (!rutaArchivo.equals("")) {
        adjunto.setDataHandler(new DataHandler(new FileDataSource(rutaArchivo)));
        adjunto.setFileName(nombreArchivo);
      }

      MimeMultipart multiParte = new MimeMultipart();
      multiParte.addBodyPart(texto);
      if (!rutaArchivo.equals("")) {
        multiParte.addBodyPart(adjunto);
      }

      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(usuarioCorreo));

      // Destinatarios varios
      for (int i = 0; i < Destinatarios.size(); i++) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(Destinatarios.get(i)));
        message.setSubject(asunto);
      }
      message.setContent(mensaje, "text/html");
      Informe.SetConectando();
      Transport t = session.getTransport("smtp");
      t.connect(usuarioCorreo, password);
      Informe.SetEnviando();
      t.sendMessage(message, message.getAllRecipients());
      t.close();
      Informe.SetEnviado(true);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      Informe.SetEnviado(false);
      return false;
    }
  }
Beispiel #6
0
  public static void sendEmail(String camName, String imageFileName)
      throws AddressException, MessagingException {

    String pw = new FileHandle("C:/Apps/pw.txt").readString();
    // Step1
    System.out.println("\n 1st ===> setup Mail Server Properties..");
    Properties mailServerProperties = System.getProperties();
    mailServerProperties.put("mail.smtp.port", "587");
    mailServerProperties.put("mail.smtp.auth", "true");
    mailServerProperties.put("mail.smtp.starttls.enable", "true");
    System.out.println("Mail Server Properties have been setup successfully..");

    // Step2
    System.out.println("\n\n 2nd ===> get Mail Session..");
    Session getMailSession = Session.getDefaultInstance(mailServerProperties, null);
    Message generateMailMessage = new MimeMessage(getMailSession);
    generateMailMessage.addRecipient(
        Message.RecipientType.TO, new InternetAddress("*****@*****.**"));
    // generateMailMessage.addRecipient(Message.RecipientType.CC, new
    // InternetAddress("*****@*****.**"));
    generateMailMessage.setSubject("WebCamFeed_Motion Alert");

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText("Motion detected on camera -> " + camName);
    Multipart multipart = new MimeMultipart();
    messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(imageFileName);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(imageFileName);
    multipart.addBodyPart(messageBodyPart);

    generateMailMessage.setContent(multipart);
    System.out.println("Mail Session has been created successfully..");

    // Step3
    System.out.println("\n\n 3rd ===> Get Session and Send mail");
    Transport transport = getMailSession.getTransport("smtp");

    // Enter your correct gmail UserID and Password
    // if you have 2FA enabled then provide App Specific Password
    transport.connect("smtp.gmail.com", "*****@*****.**", pw);
    transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
    transport.close();
  }
Beispiel #7
0
  public static void main(String[] args) throws MessagingException {
    Properties props = System.getProperties();

    // Activa SSL para smtp
    props.setProperty("mail.smtp.ssl.enable", "true");
    // Establece el puerto
    props.setProperty("mail.smtp.port", "465");

    props.setProperty("mail.transport.protocol", "smtps");
    // Activa la autenticación, mi servidor requiere autenticación
    props.setProperty("mail.smtps.auth", "true");
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    props.put("mail.smtps.host", smtpHost);

    // clase session
    Session sesion = Session.getDefaultInstance(props);
    sesion.setDebug(true);

    // Clase messaje
    Message mensaje = new MimeMessage(sesion);
    mensaje.setSubject("Archivo adjunto");
    mensaje.setFrom(new InternetAddress(deCorreo));

    mensaje.addRecipient(Message.RecipientType.TO, new InternetAddress(paraCorreo));

    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();
    // Rellena el mensaje
    messageBodyPart.setText("Aquí llevas un archivo adjunto");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    Transport t = sesion.getTransport();

    String pass = leePassword();

    t.connect(deCorreo, pass);

    t.sendMessage(mensaje, mensaje.getAllRecipients());
    t.close();
  }
Beispiel #8
0
  public static void send(AlarmManager.Alarm alarm) {

    String to = Settings.GetSettingForKey(Setting.EMAIL_ADDR);

    // ***** smtp login details *****
    // Dont save these details in a file
    // Strongly recommended to generate a single application access key from google
    // Dont use your actual password!
    String from = "@gmail.com";
    final String username = "******";
    final String password = "";

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

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

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
      message.setSubject("PiSec Alarm Notice");

      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(alarm.toString());

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

      try {
        if (!alarm.getPictureLocation().equals("")) {
          File zippedImages = zipImages(alarm);
          String filename = zippedImages.getAbsolutePath();
          DataSource source = new FileDataSource(filename);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(filename);
          multipart.addBodyPart(messageBodyPart);
        }
      } catch (Exception e) {
        Logger.Log("Unable to attach zipped images!");
      }

      message.setContent(multipart);

      Transport.send(message);
      Logger.Log("Email Sent!");

    } catch (MessagingException e) {
      e.printStackTrace();
      Logger.Log("Unable to send email! " + e.getMessage());
    }
  }
  public static void envioCorreoZimbra(
      String destinatarios,
      String asunto,
      String detalle,
      List<File> listAdjunto,
      String emailEmisor,
      String passEmail)
      throws Exception {

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

    properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    properties.put("mail.smtp.starttls.enable", true);

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

    Message mensaje = new MimeMessage(session);
    mensaje.setFrom(new InternetAddress(emailEmisor));

    try {
      mensaje.addRecipient(Message.RecipientType.TO, new InternetAddress(destinatarios));
      // Message.RecipientType.CC; con copia
      // Message.RecipientType.BCC; con copia oculta
    } catch (Exception e) {
      e.printStackTrace();
    }

    mensaje.setSubject(asunto);
    mensaje.setSentDate(new Date());

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(detalle);

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

    if (listAdjunto != null && !listAdjunto.isEmpty()) {
      for (File adjunto : listAdjunto) {
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(adjunto)));
        messageBodyPart.setFileName(adjunto.getName());
        multipart.addBodyPart(messageBodyPart);
      }
    }

    mensaje.setContent(multipart);

    System.clearProperty("javax.net.ssl.keyStore");
    System.clearProperty("javax.net.ssl.keyStorePassword");
    System.clearProperty("javax.net.ssl.trustStore");
    System.clearProperty("javax.net.ssl.trustStorePassword");

    SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
    try {
      transport.connect(emailEmisor, passEmail);
      transport.sendMessage(mensaje, mensaje.getAllRecipients());
    } finally {
      transport.close();
    }
  }
Beispiel #10
0
  /**
   * 邮件发送
   *
   * @param mailInfo
   * @param isHtml
   * @return
   * @throws MessagingException
   * @throws UnsupportedEncodingException
   */
  private boolean send(MailSenderInfo mailInfo, boolean isHtml) throws MessagingException {
    // 判断是否需要身份认证
    SMTPAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
      // 如果需要身份认证,则创建一个密码验证器
      authenticator = new SMTPAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
    // 根据session创建一个邮件消息
    Message mailMessage = new MimeMessage(sendMailSession);
    // 创建邮件发送者地址
    Address from = null;
    try {
      from = new InternetAddress(mailInfo.getFromAddress(), mailInfo.getFromName());
    } catch (UnsupportedEncodingException e) {
      from = new InternetAddress(mailInfo.getFromAddress());
    }
    // 设置邮件消息的发送者
    mailMessage.setFrom(from);
    // 创建邮件的接收者地址,并设置到邮件消息中
    Address[] to = new InternetAddress[mailInfo.getToAddress().size()];
    int i = 0;
    for (String temp : mailInfo.getToAddress()) {
      to[i++] = new InternetAddress(temp);
    }
    mailMessage.setRecipients(Message.RecipientType.TO, to);
    // 设置邮件消息的主题
    mailMessage.setSubject(mailInfo.getSubject());
    // 设置邮件消息发送的时间
    mailMessage.setSentDate(new Date());

    // 邮件对象,MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
    Multipart mainPart = new MimeMultipart();

    // 邮件正文
    BodyPart mailBody = new MimeBodyPart();
    if (isHtml) {
      // 设置HTML内容
      mailBody.setContent(mailInfo.getContent(), "text/html; charset=" + mailInfo.getCharset());
    } else {
      // 设置非HTML内容
      mailBody.setText(mailInfo.getContent());
    }
    mainPart.addBodyPart(mailBody); // 添加邮件正文至邮件对象

    // 邮件附件
    for (MailAttachment item : mailInfo.getAttachFiles()) {
      BodyPart attachment = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(item.getAbsoluteFile()); // 得到附件数据源
      attachment.setDataHandler(new DataHandler(fds)); // 得到附件本身
      // 设置文件名,并解决中文名乱码问题
      String fileName = item.getAliasName();
      try {
        attachment.setFileName(MimeUtility.encodeText(fileName));
      } catch (UnsupportedEncodingException e) {
        attachment.setFileName(fileName);
      }
      mainPart.addBodyPart(attachment); // 添加邮件附件至邮件对象
    }

    // 添加邮件内容对象
    mailMessage.setContent(mainPart);
    // 保存邮件
    mailMessage.saveChanges();
    // 发送邮件
    Transport.send(mailMessage);
    return true;
  }
Beispiel #11
0
  public boolean sendMessage() {
    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[] addressTO = null;
      if (this.Destination != null && this.Destination.length() != 0) {
        StringTokenizer TOList = getTokenizer(this.Destination);
        addressTO = new InternetAddress[TOList.countTokens()];
        for (int i = 0; i < addressTO.length; i++) {
          addressTO[i] = new InternetAddress(TOList.nextToken());
          message.addRecipient(Message.RecipientType.TO, addressTO[i]);
        }
      }

      if (this.MsgCC != null && this.MsgCC.length() != 0) {
        StringTokenizer CCList = getTokenizer(this.MsgCC);
        InternetAddress[] addressCC = new InternetAddress[CCList.countTokens()];
        for (int i = 0; i < addressCC.length; i++) {
          addressCC[i] = new InternetAddress(CCList.nextToken());
          message.addRecipient(Message.RecipientType.CC, addressCC[i]);
        }
      }
      message.setFrom(new InternetAddress(Source));
      message.setSubject(Subject);
      Content = getHtmlHeader() + Content + getHtmlFooter();
      Content = Content.replaceAll("\\{style\\}", MailStyle);

      BodyPart messageBodyPart = new MimeBodyPart();

      messageBodyPart.setText(Content);
      messageBodyPart.setContent(Content, "text/html");

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

      Iterator it = this.BinaryAttachments.iterator();
      while (it.hasNext()) {
        ByteArrayDataSource bads = (ByteArrayDataSource) it.next();

        messageBodyPart = new MimeBodyPart();
        // messageBodyPart.setDataHandler(new DataHandler(new FileDataSource("c:/test/tom.jpg")));
        messageBodyPart.setDataHandler(new DataHandler(bads));
        messageBodyPart.setFileName(bads.getName());

        multipart.addBodyPart(messageBodyPart);
      }
      message.setContent(multipart);

      Transport transport = session.getTransport(addressTO[0]);
      transport.addConnectionListener(new ConnectionHandler());
      transport.addTransportListener(new TransportHandler());
      transport.connect();
      transport.send(message);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
Beispiel #12
0
  public static String doSendMail(String mmsg, String toAddress, String subject, String filnme)
      throws Exception {
    String status = "N";
    try {
      String fromAddress = "*****@*****.**";
      String messages = "" + mmsg;

      MailSSLSocketFactory sf = new MailSSLSocketFactory();
      sf.setTrustAllHosts(true);
      Properties properties = System.getProperties();
      properties.put("mail.smtp.host", "mail.nic.in");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.ssl.enable", "true");

      properties.put("mail.smtp.port", "465");
      properties.put("mail.smtp.ssl.socketFactory", sf);
      Session session = Session.getInstance(properties);
      MimeMessage msg = new MimeMessage(session);

      msg.setFrom(new InternetAddress(fromAddress));
      msg.addRecipients(Message.RecipientType.TO, toAddress);
      msg.setSubject(subject);
      msg.setText(messages);

      Message message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(fromAddress));

      // Set To: header field of the header.
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));

      // Set Subject: header field
      message.setSubject(subject);

      BodyPart messageBodyPart = new MimeBodyPart();

      // Now set the actual message
      messageBodyPart.setText(messages);
      Multipart multipart = new MimeMultipart();

      // Set text message part
      multipart.addBodyPart(messageBodyPart);

      // Part two is attachment
      messageBodyPart = new MimeBodyPart();
      // String filename = "C:/JHRKHDCTAX_Settlement_20140721.xml";
      String filename = "C:/" + filnme;
      System.out.println(filename);
      DataSource source = new FileDataSource(filename);
      messageBodyPart.setDataHandler(new DataHandler(source));
      // messageBodyPart.setFileName("JHRKHDCTAX_Settlement_20140721.xml");
      messageBodyPart.setFileName(filnme);
      multipart.addBodyPart(messageBodyPart);

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

      Transport tr = session.getTransport("smtp");
      tr.connect("mail.nic.in", "*****@*****.**", "Vz#$5d9*pnK");
      tr.sendMessage(message, message.getAllRecipients());
      tr.close();
      status = "Y";
    } catch (AddressException ex) {
      System.out.println(ex.getMessage());
      throw new Exception("Address not Valid");
    } catch (MessagingException ex) {
      System.out.println(ex.getMessage());
      throw new Exception("Mail sending fail " + ex.getMessage());
    } catch (Exception e) {
      throw new Exception("Mail sending fail " + e.getMessage());
    }
    return status;
  }
Beispiel #13
0
  public static String send(Email2Send email, Server server) throws Exception {
    Session session;

    if (server.isAuth()) {
      Authenticator auth = new PopAuthenticator(server.getUser(), server.getPwd());
      session = Session.getInstance(getProperties(server), auth);
    } else {
      session = Session.getInstance(getProperties(server), null);
    }
    MyMessage mailMsg = new MyMessage(session); // a new email message
    InternetAddress[] addresses = null;
    try {
      if (email.getDestinatari() != null && email.getDestinatari().size() > 0) {
        addresses = InternetAddress.parse(email.getDestinatariToString(), false);
        mailMsg.setRecipients(Message.RecipientType.TO, addresses);
      } else {
        throw new MessagingException("The mail message requires a 'To' address.");
      }
      if (email.getCc() != null && email.getCc().size() > 0) {
        addresses = InternetAddress.parse(email.getCcToString(), false);
        mailMsg.setRecipients(Message.RecipientType.CC, addresses);
      }
      if (email.getBcc() != null && email.getBcc().size() > 0) {
        addresses = InternetAddress.parse(email.getBccToString(), false);
        mailMsg.setRecipients(Message.RecipientType.BCC, addresses);
      }
      if (email.getMittente() != null) {
        mailMsg.setFrom(new InternetAddress(email.getMittente()));
      } else {
        throw new MessagingException("The mail message requires a valid 'From' address.");
      }
      //
      if (email.getOggetto() != null) mailMsg.setSubject(email.getOggetto());
      // corpo e attachment
      if (email.getAllegati() != null && email.getAllegati().size() > 0) {
        BodyPart messageBodyPart = new MimeBodyPart();
        if (email.getCorpo() != null) messageBodyPart.setText(email.getCorpo());
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        for (File allegato : email.getAllegati()) {
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(allegato.getCanonicalPath());
          DataHandler dataH = new DataHandler(source);
          messageBodyPart.setDataHandler(dataH);
          messageBodyPart.setFileName(allegato.getName());
          multipart.addBodyPart(messageBodyPart);
        }
        mailMsg.setContent(multipart);
      } else {
        mailMsg.setContent(email.getCorpo(), "text/plain;charset=\"UTF-8\"");
      }

      mailMsg.setId("<CN" + System.currentTimeMillis() + "@giava.by/giavacms>");
      // mailMsg.addHeader("Message-ID",
      // "111111.11199295388525.provaProvaProva");

      mailMsg.setSentDate(new Date());
      mailMsg.saveChanges();
      // Finally, send the mail message; throws a 'SendFailedException'
      // if any of the message's recipients have an invalid address
      Transport.send(mailMsg);
    } catch (MessagingException e) {
      logger.error(e.toString());
      e.printStackTrace();
      return "";
    } catch (Exception exc) {
      logger.error(exc.toString());
      exc.printStackTrace();
      return "";
    }
    return mailMsg.getMessageID();
  }
Beispiel #14
0
  public static boolean sendEmail(
      String toAddress,
      String fromAddress,
      final String userName,
      final String password,
      String smt_auth,
      String smtp_starttls,
      String smtp_host,
      String smtp_port,
      String filepath) {

    Properties props = new Properties();
    props.put("mail.smtp.auth", smt_auth);
    props.put("mail.smtp.starttls.enable", smtp_starttls);
    props.put("mail.smtp.host", smtp_host);
    props.put("mail.smtp.port", smtp_port);

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

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(fromAddress));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));

      try {
        Date date = new Date();
        message.setSubject(
            "Test Results for " + InetAddress.getLocalHost().getHostName() + " " + date.toString());
      } catch (UnknownHostException e) {

        e.printStackTrace();
      }

      // Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();
      String newl = System.getProperty("line.separator");

      // Now set the actual message
      messageBodyPart.setText(
          "Hi,"
              + newl
              + "Please find the Html report attached."
              + newl
              + "This test report covers till 'send mail' functionality."
              + newl
              + newl
              + "Thanks & Regards,"
              + newl);

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

      // attachment
      messageBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(filepath);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(filepath);
      multipart.addBodyPart(messageBodyPart);

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

      Transport.send(message);

      return true;

    } catch (MessagingException e) {
      e.printStackTrace();
      return false;
    }
  }
Beispiel #15
0
  public static boolean SendEmail(
      String subject,
      String content,
      String SendTo,
      String CCList,
      String BCCList,
      String SendFrom,
      String AttachmentSource,
      String AttachmentFile,
      String SMTPusername,
      String SMTPpassword,
      String secureType,
      String SMTPHost,
      String SMTPPort) {

    Session session = null;

    if (secureType.equals("TLS")) {
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      session = Session.getInstance(props);
    } else if (secureType.equals("SSL")) {
      Properties props = new Properties();
      props.put("mail.smtp.host", SMTPHost);
      props.put("mail.smtp.socketFactory.port", SMTPPort);
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", SMTPPort);

      final String SMTPUsername = SMTPusername;
      final String SMTPPassword = SMTPpassword;

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

                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(SMTPUsername, SMTPPassword);
                }
              });
    }

    if (session == null) {
      return false;
    }

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(SendFrom));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(SendTo));
      if (!CCList.equals("")) {
        message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(CCList));
      }
      if (!BCCList.equals("")) {
        message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(BCCList));
      }

      message.setSubject(subject);

      if (!AttachmentFile.equals("")) {
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Fill the message
        messageBodyPart.setText(content);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(AttachmentSource);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(AttachmentFile);
        multipart.addBodyPart(messageBodyPart);
        // Put parts in message
        message.setContent(multipart);
      } else {
        message.setText(content);
      }

      if (secureType.equals("TLS")) {
        Transport transport = session.getTransport("smtp");
        transport.connect(SMTPHost, Integer.parseInt(SMTPPort), SMTPusername, SMTPpassword);
      }

      Transport.send(message);

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

    return true;
  }
  public static boolean sendMail(String fileName) throws UnknownHostException {
    boolean success = false;
    // Recipient's email ID needs to be mentioned.
    String to = Config.RECIPIENT_EMAIL_ID.getValue(); // change accordingly

    // Sender's email ID needs to be mentioned
    String from =
        Config.SENDER_EMAIL_ID.getValue(); // "*****@*****.**";//change accordingly
    final String username =
        Config.SENDER_EMAIL_ID.getValue(); // "*****@*****.**";//change accordingly
    String passwd = "";

    if (Config.DECRYPT_REQUIRED.getValueAsBoolean()) {
      try {
        passwd =
            CryptoHelper.decrypt(
                Config.SENDER_ENCRYPTED_PASSWORD.getValue()); // change accordingly
      } catch (CryptoException ex) {
        Logger.getLogger(MailHelper.class.getName())
            .log(
                Level.SEVERE,
                "Problem with sender password, not decrypted properly or wrong password ....",
                ex);
      }
    } else {
      passwd = Config.SENDER_ENCRYPTED_PASSWORD.getValue();
    }
    final String password = passwd;
    // Assuming you are sending email through relay.jangosmtp.net
    //        String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", Config.MAIL_SMTP_AUTH.getValue());
    props.put("mail.smtp.starttls.enable", Config.MAIL_SMTP_STARTTLS_ENABLE.getValue());
    props.put("mail.smtp.host", Config.MAIL_SMTP_HOST.getValue());
    props.put("mail.smtp.port", Config.MAIL_SMTP_PORT.getValue());

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

    try {
      // Create a default MimeMessage object.
      Message message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      // Set To: header field of the header.
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

      // Set Subject: header field
      message.setSubject("Testing Subject");

      // Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();

      // Now set the actual message
      messageBodyPart.setText(
          "This is message body"
              + "/n"
              + "IP of you cam is : "
              + java.net.InetAddress.getLocalHost());

      // Create a multipar message
      Multipart multipart = new MimeMultipart();

      // Set text message part
      multipart.addBodyPart(messageBodyPart);

      // Part two is attachment
      messageBodyPart = new MimeBodyPart();
      DataSource source =
          new FileDataSource(MotionMain.DIRECTORY_TO_WATCH + File.separatorChar + fileName);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(fileName);
      multipart.addBodyPart(messageBodyPart);

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

      // Send message
      Transport.send(message);
      success = true;
      System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
    return success;
  }
Beispiel #17
0
  /*
   * (non-Javadoc)
   *
   * @see org.mule.transformers.AbstractEventAwareTransformer#transform(java.lang.Object,
   *      java.lang.String, org.mule.umo.UMOEventContext)
   */
  public Object transform(Object src, String encoding, UMOEventContext context)
      throws TransformerException {

    String endpointAddress = endpoint.getEndpointURI().getAddress();
    SmtpConnector connector = (SmtpConnector) endpoint.getConnector();
    UMOMessage eventMsg = context.getMessage();

    String to = eventMsg.getStringProperty(MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress);
    String cc =
        eventMsg.getStringProperty(
            MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses());
    String bcc =
        eventMsg.getStringProperty(
            MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses());
    String from =
        eventMsg.getStringProperty(
            MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress());
    String replyTo =
        eventMsg.getStringProperty(
            MailProperties.REPLY_TO_ADDRESSES_PROPERTY, connector.getReplyToAddresses());
    String subject =
        eventMsg.getStringProperty(MailProperties.SUBJECT_PROPERTY, connector.getSubject());
    String contentType =
        eventMsg.getStringProperty(
            MailProperties.CONTENT_TYPE_PROPERTY, connector.getContentType());

    Properties headers = new Properties();
    Properties customHeaders = connector.getCustomHeaders();

    if (customHeaders != null && !customHeaders.isEmpty()) {
      headers.putAll(customHeaders);
    }

    Properties otherHeaders =
        (Properties) eventMsg.getProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY);
    if (otherHeaders != null && !otherHeaders.isEmpty()) {
      Map props = new HashMap(MuleManager.getInstance().getProperties());
      for (Iterator iterator = eventMsg.getPropertyNames().iterator(); iterator.hasNext(); ) {
        String propertyKey = (String) iterator.next();
        props.put(propertyKey, eventMsg.getProperty(propertyKey));
      }
      headers.putAll(templateParser.parse(props, otherHeaders));
    }

    if (logger.isDebugEnabled()) {
      StringBuffer buf = new StringBuffer(256);
      buf.append("Constructing email using:\n");
      buf.append("To: ").append(to);
      buf.append("From: ").append(from);
      buf.append("CC: ").append(cc);
      buf.append("BCC: ").append(bcc);
      buf.append("Subject: ").append(subject);
      buf.append("ReplyTo: ").append(replyTo);
      buf.append("Content type: ").append(contentType);
      buf.append("Payload type: ").append(src.getClass().getName());
      buf.append("Custom Headers: ").append(PropertiesUtils.propertiesToString(headers, false));
      logger.debug(buf.toString());
    }

    try {
      Message email =
          new MimeMessage(
              (Session) endpoint.getConnector().getDispatcher(endpoint).getDelegateSession());

      // set mail details
      email.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to));
      email.setSentDate(Calendar.getInstance().getTime());
      if (StringUtils.isNotBlank(from)) {
        email.setFrom(MailUtils.stringToInternetAddresses(from)[0]);
      }
      if (StringUtils.isNotBlank(cc)) {
        email.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc));
      }
      if (StringUtils.isNotBlank(bcc)) {
        email.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc));
      }
      if (StringUtils.isNotBlank(replyTo)) {
        email.setReplyTo(MailUtils.stringToInternetAddresses(replyTo));
      }
      email.setSubject(subject);

      for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext(); ) {
        Map.Entry entry = (Map.Entry) iterator.next();
        email.setHeader(entry.getKey().toString(), entry.getValue().toString());
      }

      // Create Multipart to put BodyParts in
      Multipart multipart = new MimeMultipart();

      // Create Text Message
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText("My Text");
      multipart.addBodyPart(messageBodyPart);

      // Create Attachment
      messageBodyPart = new MimeBodyPart();
      DataHandler dataHandler = (DataHandler) src;
      messageBodyPart.setDataHandler(dataHandler);
      messageBodyPart.setFileName(dataHandler.getName());
      multipart.addBodyPart(messageBodyPart);

      email.setContent(multipart);

      return email;
    } catch (Exception e) {
      throw new TransformerException(this, e);
    }
  }