Search in sources :

Example 6 with PasswordAuthentication

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

the class SendAttachmentInEmail 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");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Now set the actual message
        messageBodyPart.setText("This is message body");
        // Create a multipar message
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "/home/manisha/file.txt";
        DataSource source = new FileDataSource(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);
        System.out.println("Sent message successfully....");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 7 with PasswordAuthentication

use of javax.mail.PasswordAuthentication in project jmeter by apache.

the class MailerModel method sendMail.

/**
     * Sends a mail with the given parameters using SMTP.
     *
     * @param from
     *            the sender of the mail as shown in the mail-client.
     * @param vEmails
     *            all receivers of the mail. The receivers are seperated by
     *            commas.
     * @param subject
     *            the subject of the mail.
     * @param attText
     *            the message-body.
     * @param smtpHost
     *            the smtp-server used to send the mail.
     * @param smtpPort the smtp-server port used to send the mail.
     * @param user the login used to authenticate
     * @param password the password used to authenticate
     * @param mailAuthType {@link MailAuthType} Security policy
     * @param debug Flag whether debug messages for the mail session should be generated
     * @throws AddressException If mail address is wrong
     * @throws MessagingException If building MimeMessage fails
     */
public void sendMail(String from, List<String> vEmails, String subject, String attText, String smtpHost, String smtpPort, final String user, final String password, MailAuthType mailAuthType, boolean debug) throws MessagingException {
    InternetAddress[] address = new InternetAddress[vEmails.size()];
    for (int k = 0; k < vEmails.size(); k++) {
        address[k] = new InternetAddress(vEmails.get(k));
    }
    // create some properties and get the default Session
    Properties props = new Properties();
    props.put(MAIL_SMTP_HOST, smtpHost);
    // property values are strings
    props.put(MAIL_SMTP_PORT, smtpPort);
    Authenticator authenticator = null;
    if (mailAuthType != MailAuthType.NONE) {
        props.put(MAIL_SMTP_AUTH, "true");
        switch(mailAuthType) {
            case SSL:
                props.put(MAIL_SMTP_SOCKETFACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
                break;
            case TLS:
                props.put(MAIL_SMTP_STARTTLS, "true");
                break;
            default:
                break;
        }
    }
    if (!StringUtils.isEmpty(user)) {
        authenticator = new javax.mail.Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        };
    }
    Session session = Session.getInstance(props, authenticator);
    session.setDebug(debug);
    // create a message
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setText(attText);
    Transport.send(msg);
}
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) Authenticator(javax.mail.Authenticator) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) Session(javax.mail.Session)

Example 8 with PasswordAuthentication

use of javax.mail.PasswordAuthentication in project Gargoyle by callakrsos.

the class EmailAttachmentSender method sendEmailWithAttachments.

public static void sendEmailWithAttachments(String host, String port, final String userName, final String password, String toAddress, String subject, String message, String[] attachFiles) throws AddressException, MessagingException {
    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.user", userName);
    properties.put("mail.password", password);
    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };
    Session session = Session.getInstance(properties, auth);
    // creates a new e-mail message
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(message, "text/html");
    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    // adds attachments
    if (attachFiles != null && attachFiles.length > 0) {
        for (String filePath : attachFiles) {
            MimeBodyPart attachPart = new MimeBodyPart();
            try {
                attachPart.attachFile(filePath);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            multipart.addBodyPart(attachPart);
        }
    }
    // sets the multi-part as e-mail's content
    msg.setContent(multipart);
    // sends the e-mail
    Transport.send(msg);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) IOException(java.io.IOException) Properties(java.util.Properties) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) Session(javax.mail.Session)

Example 9 with PasswordAuthentication

use of javax.mail.PasswordAuthentication in project Gargoyle by callakrsos.

the class MailPopReceiver method receiveEmail.

public void receiveEmail() {
    try {
        //1) get the session object  
        //new Properties();
        Properties properties = System.getProperties();
        properties.put("mail.pop3.host", popHost);
        properties.put("mail.user", userName);
        properties.put("mail.from", hostEmailAddr);
        properties.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.pop3.socketFactory.port", "995");
        properties.put("mail.pop3.port", "995");
        properties.setProperty("mail.pop3.socketFactory.fallback", "false");
        if (this.proxy != null) {
            String hostName = proxy.getHostName();
            int port = proxy.getPort();
            String value = port + "";
            properties.put("proxySet", "true");
            properties.put("socksProxyHost", hostName);
            properties.put("socksProxyPort", value);
            properties.put("http.proxyHost", hostName);
            properties.put("http.proxyPort", port + "");
            properties.put("https.proxyHost", hostName);
            properties.put("https.proxyPort", port + "");
            //#####################################
            properties.setProperty("proxySet", "true");
            properties.setProperty("socksProxyHost", hostName);
            properties.setProperty("socksProxyPort", port + "");
            properties.setProperty("http.proxyHost", hostName);
            properties.setProperty("http.proxyPort", port + "");
            properties.setProperty("https.proxyHost", hostName);
            properties.setProperty("https.proxyPort", port + "");
        }
        Authenticator authenticator = new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(hostEmailAddr, password);
            }
        };
        Session emailSession = Session.getInstance(properties, authenticator);
        //			Session emailSession = Session.getDefaultInstance(properties);
        emailSession.setDebug(debug);
        //2) create the POP3 store object and connect with the pop server  
        //			POP3Store emailStore = (POP3Store) emailSession.getStore(type);
        URLName url = new URLName(type, popHost, 995, "", hostEmailAddr, password);
        POP3SSLStore emailStore = new POP3SSLStore(emailSession, url);
        System.out.println(emailStore.isSSL());
        emailStore.connect();
        System.out.println("connected.");
        //3) create the folder object and open it  
        Folder emailFolder = emailStore.getFolder("INBOX");
        emailFolder.open(Folder.READ_ONLY);
        //4) retrieve the messages from the folder in an array and print it  
        Message[] messages = emailFolder.getMessages();
        for (int i = 0; i < messages.length; i++) {
            Message message = messages[i];
            System.out.println("---------------------------------");
            System.out.println("Email Number " + (i + 1));
            System.out.println("Subject: " + message.getSubject());
            System.out.println("From: " + message.getFrom()[0]);
            System.out.println("Text: " + message.getContent().toString());
        }
        //5) close the store and folder objects  
        emailFolder.close(false);
        emailStore.close();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : Message(javax.mail.Message) MessagingException(javax.mail.MessagingException) URLName(javax.mail.URLName) IOException(java.io.IOException) Properties(java.util.Properties) Folder(javax.mail.Folder) POP3SSLStore(com.sun.mail.pop3.POP3SSLStore) NoSuchProviderException(javax.mail.NoSuchProviderException) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) Session(javax.mail.Session)

Example 10 with PasswordAuthentication

use of javax.mail.PasswordAuthentication in project opennms by OpenNMS.

the class JavaMailer2 method createAuthenticator.

/**
 * Helper method to create an Authenticator based on Password Authentication
 *
 * @param user a {@link java.lang.String} object.
 * @param password a {@link java.lang.String} object.
 * @return a {@link javax.mail.Authenticator} object.
 */
public Authenticator createAuthenticator(final String user, final String password) {
    Authenticator auth;
    auth = new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password);
        }
    };
    return auth;
}
Also used : Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication)

Aggregations

PasswordAuthentication (javax.mail.PasswordAuthentication)26 Session (javax.mail.Session)21 Properties (java.util.Properties)19 MimeMessage (javax.mail.internet.MimeMessage)19 InternetAddress (javax.mail.internet.InternetAddress)18 Message (javax.mail.Message)15 MessagingException (javax.mail.MessagingException)14 Authenticator (javax.mail.Authenticator)13 Date (java.util.Date)6 MimeBodyPart (javax.mail.internet.MimeBodyPart)6 MimeMultipart (javax.mail.internet.MimeMultipart)6 Multipart (javax.mail.Multipart)5 IOException (java.io.IOException)3 DataHandler (javax.activation.DataHandler)3 FileDataSource (javax.activation.FileDataSource)3 File (java.io.File)2 GeneralSecurityException (java.security.GeneralSecurityException)2 DataSource (javax.activation.DataSource)2 BodyPart (javax.mail.BodyPart)2 PropertiesUtil (com.myspringboot.utils.PropertiesUtil)1