Search in sources :

Example 51 with Message

use of javax.mail.Message 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)

Example 52 with Message

use of javax.mail.Message in project pratilipi by Pratilipi.

the class EmailUtil method sendMail.

public static void sendMail(String senderName, String senderEmail, InternetAddress[] recipients, InternetAddress[] cc, String subject, String body) throws UnexpectedServerException {
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(senderEmail, senderName));
        msg.addRecipients(Message.RecipientType.TO, recipients);
        msg.addRecipients(Message.RecipientType.CC, cc);
        // TODO: Uncomment when we migrate to other email service providers
        //			msg.addRecipient( Message.RecipientType.BCC, new InternetAddress( "mail-archive@pratilipi.com", "Mail Archive" ) );
        msg.setSubject(subject);
        msg.setContent(body, "text/html; charset=UTF-8");
        logger.log(Level.INFO, "Sending mail");
        Transport.send(msg);
    } catch (UnsupportedEncodingException | MessagingException e) {
        //			logger.log( Level.SEVERE, "Failed to send mail to " + recipientEmail + ".", e );
        throw new UnexpectedServerException();
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 53 with Message

use of javax.mail.Message 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 54 with Message

use of javax.mail.Message 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 55 with Message

use of javax.mail.Message in project SpringStepByStep by JavaProgrammerLB.

the class SendEmail method main.

public static void main(String[] args) {
    // Recipient's email ID needs to be mentioned.
    String to = "destinationemail@gmail.com";
    // Sender's email ID needs to be mentioned
    String from = "fromemail@gmail.com";
    //change accordingly
    final String username = "manishaspatil";
    //change accordingly
    final String password = "******";
    // Assuming you are sending email through relay.jangosmtp.net
    String host = "relay.jangosmtp.net";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "25");
    // 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");
        // Now set the actual message
        message.setText("Hello, this is sample for to check send " + "email using JavaMailAPI ");
        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Aggregations

Message (javax.mail.Message)149 MimeMessage (javax.mail.internet.MimeMessage)81 MessagingException (javax.mail.MessagingException)53 InternetAddress (javax.mail.internet.InternetAddress)48 Folder (javax.mail.Folder)41 Test (org.junit.Test)40 Session (javax.mail.Session)37 Properties (java.util.Properties)36 Store (javax.mail.Store)28 Date (java.util.Date)19 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)19 MimeMultipart (javax.mail.internet.MimeMultipart)18 Mailbox (org.jvnet.mock_javamail.Mailbox)18 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 PasswordAuthentication (javax.mail.PasswordAuthentication)15 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)13 Multipart (javax.mail.Multipart)13 Address (javax.mail.Address)11 HashMap (java.util.HashMap)8