Search in sources :

Example 71 with Session

use of javax.mail.Session in project GNS by MobilityFirst.

the class Email method emailTLS.

/**
   * Attempts to use TLS to send a message to the recipient.
   * If suppressWarning is true no warning message will be logged if this fails.
   *
   * @param subject
   * @param recipient
   * @param text
   * @param suppressWarning
   * @return true if the message was sent
   */
// TLS doesn't work with Dreamhost
public static boolean emailTLS(String subject, String recipient, String text, boolean suppressWarning) {
    final String username = Config.getGlobalString(GNSConfig.GNSC.ADMIN_EMAIL);
    final String contactString = Config.getGlobalString(GNSConfig.GNSC.ADMIN_PASSWORD);
    try {
        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() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, contactString);
            }
        });
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(Config.getGlobalString(GNSConfig.GNSC.SUPPORT_EMAIL)));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
        message.setSubject(subject);
        message.setText(text);
        Transport.send(message);
        getLogger().log(Level.FINE, "Successfully sent email to {0} with message: {1}", new Object[] { recipient, text });
        return true;
    } catch (Exception e) {
        if (!suppressWarning) {
            getLogger().log(Level.WARNING, "Unable to send email: {0}", e);
        }
        return false;
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) MessagingException(javax.mail.MessagingException) GeneralSecurityException(java.security.GeneralSecurityException) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 72 with Session

use of javax.mail.Session in project GNS by MobilityFirst.

the class Email method emailSSL.

/**
   * Attempts to use SSL to send a message to the recipient.
   * If suppressWarning is true no warning message will be logged if this fails.
   *
   * @param subject
   * @param recipient
   * @param text
   * @param suppressWarning
   * @return true if the message was sent
   */
public static boolean emailSSL(String subject, String recipient, String text, boolean suppressWarning) {
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(Config.getGlobalString(GNSConfig.GNSC.ADMIN_EMAIL), Config.getGlobalString(GNSConfig.GNSC.ADMIN_PASSWORD));
            }
        });
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(Config.getGlobalString(GNSConfig.GNSC.SUPPORT_EMAIL)));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
        message.setSubject(subject);
        message.setText(text);
        Transport.send(message);
        getLogger().log(Level.FINE, "Successfully sent email to {0} with message: {1}", new Object[] { recipient, text });
        return true;
    } catch (Exception e) {
        if (!suppressWarning) {
            getLogger().log(Level.WARNING, "Unable to send email: {0}", e);
        }
        return false;
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) MessagingException(javax.mail.MessagingException) GeneralSecurityException(java.security.GeneralSecurityException) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 73 with Session

use of javax.mail.Session in project LAMSADE-tools by LAntoine.

the class Util method sendEmail.

/**
	 * Sends an email to an address passed by parameter. If there is an error
	 * other than lack of an Internet connection, the program will exit with a
	 * stack trace.
	 *
	 * @param to_address
	 *            the address to send the email to
	 * @param filename
	 *            if it's not empty, it will send the file referenced to by the
	 *            filename as an attachment
	 * @throws IllegalStateException
	 * @returns 0 if it all went well, -1 if there was some error.
	 */
public static int sendEmail(String to_address, String filename) throws IllegalStateException {
    int smtp_port = 465;
    String smtp_host = "smtp.gmail.com";
    String smtp_username = "lamsade.tools@gmail.com";
    String smtp_password = "z}}VC_-7{3bk^?*q^qZ4Z>G<5cgN&un&@>wU`gyza]kR(2v/&j!*6*s?H[^w=52e";
    Properties props = System.getProperties();
    props.put("mail.smtp.host", smtp_host);
    props.put("mail.smtps.auth", true);
    props.put("mail.smtps.starttls.enable", true);
    props.put("mail.smtps.debug", true);
    Session session = Session.getInstance(props, null);
    Message message = new MimeMessage(session);
    logger.info("Trying to send an email to " + to_address);
    try {
        try {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to_address));
        } catch (AddressException e) {
            logger.error("There is a problem with the address");
            throw new IllegalStateException(e);
        }
        message.setFrom(new InternetAddress(smtp_username));
        if (filename == "") {
            message.setSubject("Email Test Subject");
            message.setText("Email Test Body");
        } else {
            Multipart multipart = new MimeMultipart();
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent("Une conference a été partagée avec vous", "text/html");
            MimeBodyPart attachPart = new MimeBodyPart();
            String attachFile = filename;
            attachPart.attachFile(attachFile);
            // adds parts to the multipart
            multipart.addBodyPart(messageBodyPart);
            multipart.addBodyPart(attachPart);
            // sets the multipart as message's content
            message.setContent(multipart);
        }
        Transport transport = session.getTransport("smtps");
        try {
            transport.connect(smtp_host, smtp_port, smtp_username, smtp_password);
        } catch (MessagingException e) {
            logger.debug("There seems to be a problem with the connection. Try again later");
            return -1;
        }
        try {
            transport.sendMessage(message, message.getAllRecipients());
        } catch (SendFailedException e) {
            logger.error("Something went wrong trying to send the message");
            throw new IllegalStateException(e);
        }
        transport.close();
    } catch (MessagingException e) {
        logger.error("Something went wrong with building the message");
        throw new IllegalStateException(e);
    } catch (IOException e) {
        logger.error("Error in trying to add the attachment");
        throw new IllegalStateException(e);
    }
    logger.info("Email sent successfully");
    return 0;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) SendFailedException(javax.mail.SendFailedException) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) Properties(java.util.Properties) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) MimeBodyPart(javax.mail.internet.MimeBodyPart) Transport(javax.mail.Transport) Session(javax.mail.Session)

Example 74 with Session

use of javax.mail.Session in project OpenAM by OpenRock.

the class AMSendMail method postMail.

/**
     * Posts e-mail messages to users. This method will wait on for the timeouts
     * when the specified host is down. Use this method in a separate thread so
     * that it will not hang when the mail server is down.
     *
     * @param recipients A String array of e-mail addresses to be sent to
     * @param subject The e-mail subject
     * @param message The content contained in the e-mail
     * @param from The sending e-mail address
     * @param mimeType The MIME type of the e-mail
     * @param charset The charset used in e-mail encoding
     * @exception MessagingException if there is any error in sending e-mail
     */
public void postMail(String[] recipients, String subject, String message, String from, String mimeType, String charset) throws MessagingException {
    boolean debug = false;
    // create some properties and get the default mail Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);
    // create a message object
    MimeMessage 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
    if (charset == null) {
        msg.setSubject(subject);
        msg.setContent(message, mimeType);
    } else {
        charset = BrowserEncoding.mapHttp2JavaCharset(charset);
        msg.setSubject(subject, charset);
        msg.setContent(message, mimeType + "; charset=" + charset);
    }
    // Transport the message now
    Transport.send(msg);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) Session(javax.mail.Session)

Example 75 with Session

use of javax.mail.Session in project OpenAM by OpenRock.

the class AMSendMail method postMail.

/**
     * Posts e-mail messages to users. This method will wait on for the timeouts
     * when the specified host is down. Use this method in a separate thread so
     * that it will not hang when the mail server is down.
     *  
     * @param recipients A String array of e-mail addresses to be sent to
     * @param subject The e-mail subject
     * @param message The content contained in the e-mail
     * @param from The sending e-mail address
     * @param mimeType The MIME type of the e-mail
     * @param charset The charset used in e-mail encoding
     * @param host The host name to connect to send e-mail
     * @param port The host port to connect to send e-mail 
     * @param user The user name used to authenticate to the host
     * @param password The user password used to authenticate to the host
     * @param ssl A boolean to indicate whether SSL is needed to connect to the host 
     * @exception MessagingException if there is any error in sending e-mail
     */
public void postMail(String[] recipients, String subject, String message, String from, String mimeType, String charset, String host, String port, String user, String password, boolean ssl) throws MessagingException {
    boolean debug = false;
    Properties moduleProps = new Properties();
    moduleProps.put("mail.smtp.host", host);
    moduleProps.put("mail.debug", "true");
    moduleProps.put("mail.smtp.port", port);
    moduleProps.put("mail.smtp.socketFactory.port", port);
    if (ssl) {
        moduleProps.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }
    moduleProps.put("mail.smtp.socketFactory.fallback", "false");
    Session session;
    // create some properties and get the mail Session
    if (user == null || password == null) {
        session = Session.getInstance(moduleProps);
    } else {
        moduleProps.put("mail.smtp.auth", "true");
        session = Session.getInstance(moduleProps, new AMUserNamePasswordAuthenticator(user, password));
    }
    session.setDebug(debug);
    // create a message object
    MimeMessage 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
    if (charset == null) {
        msg.setSubject(subject);
        msg.setContent(message, mimeType);
    } else {
        charset = BrowserEncoding.mapHttp2JavaCharset(charset);
        msg.setSubject(subject, charset);
        msg.setContent(message, mimeType + "; charset=" + charset);
    }
    // Transport the message now
    Transport.send(msg);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Session(javax.mail.Session)

Aggregations

Session (javax.mail.Session)110 MimeMessage (javax.mail.internet.MimeMessage)72 Properties (java.util.Properties)66 InternetAddress (javax.mail.internet.InternetAddress)49 MessagingException (javax.mail.MessagingException)47 Message (javax.mail.Message)31 Test (org.junit.Test)30 Transport (javax.mail.Transport)28 JMSession (com.zimbra.cs.util.JMSession)20 PasswordAuthentication (javax.mail.PasswordAuthentication)19 Date (java.util.Date)17 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 MimeMultipart (javax.mail.internet.MimeMultipart)16 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)15 IOException (java.io.IOException)15 SharedByteArrayInputStream (javax.mail.util.SharedByteArrayInputStream)15 Authenticator (javax.mail.Authenticator)12 Multipart (javax.mail.Multipart)11 NoSuchProviderException (javax.mail.NoSuchProviderException)10 BodyPart (javax.mail.BodyPart)9