Esempio n. 1
0
 public static void sendEmailByJava(String subject, String content, List<String> address)
     throws MailingException {
   Transport transport = null;
   try {
     Smtp smtp = new Smtp();
     // Create the mail session
     Session mailSession;
     mailSession = Session.getInstance(smtp.toProperties());
     // Create the connection
     transport = mailSession.getTransport(smtp.getKindConnection());
     transport.connect(smtp.getHost(), smtp.getUser(), smtp.getPassword());
     InternetAddress fromAddress = null;
     try {
       fromAddress =
           new InternetAddress(
               MiddlewareProperties.NOTIFICATIONS_EMAIL_ADDRESS, "WB-API Notifications");
     } catch (UnsupportedEncodingException e) {
     }
     if (address != null && !address.isEmpty()) {
       MimeMessage msg = new MimeMessage(mailSession);
       msg.setSubject(subject, "utf-8");
       InternetAddress[] addressTo = new InternetAddress[address.size()];
       for (int i = 0; i < address.size(); i++) {
         addressTo[i] = new InternetAddress(address.get(i));
       }
       // Set recipient mail
       if (fromAddress != null) {
         msg.setFrom(fromAddress);
       }
       msg.setRecipients(Message.RecipientType.BCC, addressTo);
       // Set body text
       MimeBodyPart messageBodyPart = new MimeBodyPart();
       messageBodyPart.setContent(content, "text/html; charset=utf-8");
       // Multipart message
       Multipart multipart = new MimeMultipart();
       multipart.addBodyPart(messageBodyPart);
       msg.setContent(multipart);
       // Send the message
       try {
         transport.sendMessage(msg, msg.getAllRecipients());
       } catch (MessagingException e) {
         logger.error(e);
         throw new MailingException(e);
       }
     } else {
       logger.debug(
           "Trying to send a mail to a null or empty list of recipients. This is the content of the message:\n '"
               + content
               + "'");
     }
     logger.debug("Email sent.");
   } catch (Exception e) {
     logger.error(e);
     throw new MailingException(e);
   } finally {
     try {
       if (transport != null && transport.isConnected()) {
         // Close the email connection
         transport.close();
       }
     } catch (MessagingException e) {
       logger.error(e);
     }
   }
 }
 protected void sendFinished() throws Exception {
   if (transport.isConnected()) {
     transport.close();
   }
 }