Search in sources :

Example 21 with Session

use of javax.mail.Session in project libresonic by Libresonic.

the class RecoverController method emailPassword.

/*
    * e-mail user new password via configured Smtp server
    */
private boolean emailPassword(String password, String username, String email) {
    /* Default to protocol smtp when SmtpEncryption is set to "None" */
    String prot = "smtp";
    if (settingsService.getSmtpServer() == null || settingsService.getSmtpServer().isEmpty()) {
        LOG.warn("Can not send email; no Smtp server configured.");
        return false;
    }
    Properties props = new Properties();
    if (settingsService.getSmtpEncryption().equals("SSL/TLS")) {
        prot = "smtps";
        props.put("mail." + prot + ".ssl.enable", "true");
    } else if (settingsService.getSmtpEncryption().equals("STARTTLS")) {
        prot = "smtp";
        props.put("mail." + prot + ".starttls.enable", "true");
    }
    props.put("mail." + prot + ".host", settingsService.getSmtpServer());
    props.put("mail." + prot + ".port", settingsService.getSmtpPort());
    /* use authentication when SmtpUser is configured */
    if (settingsService.getSmtpUser() != null && !settingsService.getSmtpUser().isEmpty()) {
        props.put("mail." + prot + ".auth", "true");
    }
    Session session = Session.getInstance(props, null);
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(settingsService.getSmtpFrom()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Libresonic Password");
        message.setText("Hi there!\n\n" + "You have requested to reset your Libresonic password.  Please find your new login details below.\n\n" + "Username: " + username + "\n" + "Password: " + password + "\n\n" + "--\n" + "Your Libresonic server\n" + "libresonic.org");
        message.setSentDate(new Date());
        Transport trans = session.getTransport(prot);
        try {
            if (props.get("mail." + prot + ".auth") != null && props.get("mail." + prot + ".auth").equals("true")) {
                trans.connect(settingsService.getSmtpServer(), settingsService.getSmtpUser(), settingsService.getSmtpPassword());
            } else {
                trans.connect();
            }
            trans.sendMessage(message, message.getAllRecipients());
        } finally {
            trans.close();
        }
        return true;
    } catch (Exception x) {
        LOG.warn("Failed to send email.", x);
        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) Transport(javax.mail.Transport) Date(java.util.Date) Session(javax.mail.Session)

Example 22 with Session

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

the class Email method simpleMail.

/**
   *
   * @param subject
   * @param recipient
   * @param text
   * @param suppressWarning
   * @return true if the mail was sent
   */
public static boolean simpleMail(String subject, String recipient, String text, boolean suppressWarning) {
    try {
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        Properties props = new Properties();
        props.setProperty("mail.smtp.ssl.enable", "true");
        //props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        Session session = Session.getInstance(props);
        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);
        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
        try {
            t.connect(SMTP_HOST, Config.getGlobalString(GNSConfig.GNSC.ADMIN_EMAIL), Config.getGlobalString(GNSConfig.GNSC.ADMIN_PASSWORD));
            t.sendMessage(message, message.getAllRecipients());
            getLogger().log(Level.FINE, "Email response: {0}", t.getLastServerResponse());
        } finally {
            t.close();
        }
        getLogger().log(Level.FINE, "Successfully sent email to {0} with message: {1}", new Object[] { recipient, text });
        return true;
    } catch (GeneralSecurityException | MessagingException e) {
        if (!suppressWarning) {
            getLogger().log(Level.WARNING, "Unable to send email: {0}", e);
        }
        return false;
    }
}
Also used : MailSSLSocketFactory(com.sun.mail.util.MailSSLSocketFactory) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) GeneralSecurityException(java.security.GeneralSecurityException) Properties(java.util.Properties) Session(javax.mail.Session) SMTPTransport(com.sun.mail.smtp.SMTPTransport)

Example 23 with Session

use of javax.mail.Session in project Smartcity-Smarthouse by TechnionYP5777.

the class Communicate method throughEmail.

/**
     * based on:
     * http://www.javatpoint.com/example-of-sending-email-using-java-mail-api-through-gmail-server
     * 
     * @param a
     *            an Authentactor of the fromMail email address param
     * @return a string representing the state of the request, or null if the
     *         request failed
     */
public static String throughEmail(final String fromMail, final Authenticator a, final String $, final String msg) {
    final Properties properties = System.getProperties();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.socketFactory.port", "465");
    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.port", "465");
    final Session session = Session.getDefaultInstance(properties, a);
    try {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromMail));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress($));
        message.setSubject("SmartHouse Alert!");
        message.setText(msg);
        // Send message
        Transport.send(message);
    } catch (final MessagingException mex) {
        log.error("A messaging error occurred", mex);
        return null;
    }
    return "The e-mail was sent to:" + $;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Session(javax.mail.Session)

Example 24 with Session

use of javax.mail.Session in project selenium-tests by Wikia.

the class EmailUtils method deleteAllEmails.

public static void deleteAllEmails(String userName, String password) {
    try {
        // establishing connections
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        Session session = Session.getDefaultInstance(props, null);
        session.setDebug(false);
        Store store = session.getStore("imaps");
        store.connect("imap.googlemail.com", userName, password);
        // getInbox
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        Message[] messages = inbox.getMessages();
        if (messages.length != 0) {
            for (int i = 0; i < messages.length; i++) {
                messages[i].setFlag(Flags.Flag.DELETED, true);
            }
        } else {
            PageObjectLogging.log("Mail", "There are no messages in inbox", true);
        }
        store.close();
    } catch (NoSuchProviderException e) {
        PageObjectLogging.log("Mail", e, false);
    } catch (MessagingException e) {
        PageObjectLogging.log("Mail", e, false);
    }
}
Also used : Message(javax.mail.Message) MessagingException(javax.mail.MessagingException) Store(javax.mail.Store) Properties(java.util.Properties) Folder(javax.mail.Folder) NoSuchProviderException(javax.mail.NoSuchProviderException) Session(javax.mail.Session)

Example 25 with Session

use of javax.mail.Session in project selenium-tests by Wikia.

the class EmailUtils method getFirstEmailContent.

public static String getFirstEmailContent(String userName, String password, String subject) {
    try {
        PageObjectLogging.logInfo("Checking emails for " + userName + " that contain '" + subject + "'");
        // establishing connections
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.googlemail.com", userName, password);
        // getInbox
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        Message[] messages = null;
        boolean forgottenPasswordMessageFound = false;
        Message magicMessage = null;
        for (int i = 0; !forgottenPasswordMessageFound; i++) {
            messages = inbox.getMessages();
            PageObjectLogging.log("Mail", "Waiting for the message", true);
            Thread.sleep(2000);
            for (Message message : messages) {
                if (message.getSubject().contains(subject)) {
                    forgottenPasswordMessageFound = true;
                    magicMessage = message;
                }
            }
            if (i > 15) {
                throw new WebDriverException("Mail timeout exceeded");
            }
        }
        PageObjectLogging.log("Mail", "Mail arrived", true);
        Message m = magicMessage;
        String line;
        StringBuilder builder = new StringBuilder();
        InputStreamReader in = new InputStreamReader(m.getInputStream());
        BufferedReader reader = new BufferedReader(in);
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        store.close();
        return builder.toString();
    } catch (NoSuchProviderException e) {
        PageObjectLogging.log("getFirstEmailContent", e, false);
        throw new WebDriverException();
    } catch (MessagingException | IOException | InterruptedException e) {
        PageObjectLogging.log("getFirstEmailContent", e, false);
        throw new WebDriverException();
    }
}
Also used : Message(javax.mail.Message) InputStreamReader(java.io.InputStreamReader) MessagingException(javax.mail.MessagingException) Store(javax.mail.Store) IOException(java.io.IOException) Properties(java.util.Properties) Folder(javax.mail.Folder) BufferedReader(java.io.BufferedReader) NoSuchProviderException(javax.mail.NoSuchProviderException) Session(javax.mail.Session) WebDriverException(org.openqa.selenium.WebDriverException)

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