Search in sources :

Example 6 with Authenticator

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

the class SendHTMLEmailWithTemplate method main.

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    try {
        props.load(new FileInputStream(new File("settings.properties")));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    Session session = Session.getDefaultInstance(props, new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username", "******");
        }
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
        message.setSubject("Testing Subject");
        BodyPart body = new MimeBodyPart();
        // freemarker stuff.
        Configuration cfg = new Configuration();
        Template template = cfg.getTemplate("html-mail-template.ftl");
        Map<String, String> rootMap = new HashMap<String, String>();
        rootMap.put("to", "liubei");
        rootMap.put("body", "Sample html email using freemarker");
        rootMap.put("from", "liubei");
        Writer out = new StringWriter();
        template.process(rootMap, out);
        // freemarker stuff ends.
        /* you can add html tags in your text to decorate it. */
        body.setContent(out.toString(), "text/html");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(body);
        body = new MimeBodyPart();
        String filename = "hello.txt";
        DataSource source = new FileDataSource(filename);
        body.setDataHandler(new DataHandler(source));
        body.setFileName(filename);
        multipart.addBodyPart(body);
        message.setContent(multipart, "text/html;charset=utf-8");
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    System.out.println("Done....");
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) Template(freemarker.template.Template) StringWriter(java.io.StringWriter) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) StringWriter(java.io.StringWriter) Writer(java.io.Writer) Session(javax.mail.Session)

Example 7 with Authenticator

use of javax.mail.Authenticator in project nhin-d by DirectProject.

the class MessageServiceImplService method requestStatus.

@Override
public StatusResponseType requestStatus(StatusRefType body) {
    List<String> msgs = body.getMessageID();
    StatusResponseType response = new StatusResponseType();
    try {
        checkAuth(response);
        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getInstance(imapProps, auth);
        session.setDebug(true);
        if (msgs.size() > 0) {
            Store store = session.getStore(new javax.mail.URLName("imaps://" + username));
            store.connect(getImapHost(), Integer.valueOf(getImapPort()).intValue(), username, password);
            for (int x = 0; x < msgs.size(); x++) {
                String msgid = msgs.get(x);
                MessageIDTerm messageIdTerm = new MessageIDTerm(msgid);
                IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
                folder.open(Folder.READ_ONLY);
                SearchTerm st = messageIdTerm;
                IMAPMessage[] msgsearch = (IMAPMessage[]) folder.search(st);
                if (msgsearch.length > 0) {
                    Flags flags = msgsearch[0].getFlags();
                    Flag[] inboxflags = flags.getSystemFlags();
                    String[] listofflags = new String[inboxflags.length];
                    listofflags = setSystemFlags(inboxflags);
                    setMessageIdStatus(msgid, listofflags, response.getMessageIDAndStatus());
                }
            }
        }
    } catch (AddressException e) {
        log.error(e);
    } catch (MessagingException e) {
        log.error(e);
    } catch (Exception e) {
        log.error(e);
    }
    return response;
}
Also used : MessageIDTerm(javax.mail.search.MessageIDTerm) MessagingException(javax.mail.MessagingException) IMAPFolder(com.sun.mail.imap.IMAPFolder) Store(javax.mail.Store) Flags(javax.mail.Flags) SearchTerm(javax.mail.search.SearchTerm) Flag(javax.mail.Flags.Flag) StatusResponseType(org.nhindirect.schema.edge.ws.StatusResponseType) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) InvalidPropertyException(org.springframework.beans.InvalidPropertyException) IOException(java.io.IOException) AddressException(javax.mail.internet.AddressException) IMAPMessage(com.sun.mail.imap.IMAPMessage) Authenticator(javax.mail.Authenticator) Session(javax.mail.Session)

Example 8 with Authenticator

use of javax.mail.Authenticator in project JMRI by JMRI.

the class MailMessage method prepare.

/**
     * sets up needed parts for sending email message presumes any needed sets
     * have been done first
     */
public void prepare() {
    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", pProtocol);
        props.put("mail.smtp.starttls.enable", pTls);
        if (mailhost != null) {
            props.put("mail.smtp.host", mailhost);
        }
        props.put("mail.smtp.auth", pAuth);
        Authenticator auth = new SMTPAuthenticator();
        // Get a Session object
        session = Session.getInstance(props, auth);
        if (log.isDebugEnabled()) {
            session.setDebug(true);
        }
        // construct the message
        msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if (bcc != null) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }
        msg.setSubject(subject);
        // We need a multipart message to hold attachment.
        mp = new MimeMultipart();
    } catch (MessagingException e) {
        log.warn("Exception in prepare", e);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Authenticator(javax.mail.Authenticator)

Example 9 with Authenticator

use of javax.mail.Authenticator in project tomee by apache.

the class EmailService method lowerCase.

@POST
public String lowerCase(final String message) {
    try {
        //Create some properties and get the default Session
        final Properties props = new Properties();
        props.put("mail.smtp.host", "your.mailserver.host");
        props.put("mail.debug", "true");
        final Session session = Session.getInstance(props, new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("MyUsername", "MyPassword");
            }
        });
        //Set this just to see some internal logging
        session.setDebug(true);
        //Create a message
        final MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("your@email.address"));
        final InternetAddress[] address = { new InternetAddress("user@provider.com") };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail API test");
        msg.setSentDate(new Date());
        msg.setText(message, "UTF-8");
        Transport.send(msg);
    } catch (final MessagingException e) {
        return "Failed to send message: " + e.getMessage();
    }
    return "Sent";
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Authenticator(javax.mail.Authenticator) Date(java.util.Date) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication) POST(javax.ws.rs.POST)

Example 10 with Authenticator

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

Aggregations

Authenticator (javax.mail.Authenticator)17 Properties (java.util.Properties)12 Session (javax.mail.Session)12 MessagingException (javax.mail.MessagingException)10 PasswordAuthentication (javax.mail.PasswordAuthentication)9 InternetAddress (javax.mail.internet.InternetAddress)9 MimeMessage (javax.mail.internet.MimeMessage)9 IOException (java.io.IOException)7 Message (javax.mail.Message)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 MimeBodyPart (javax.mail.internet.MimeBodyPart)4 Date (java.util.Date)3 DataHandler (javax.activation.DataHandler)3 Folder (javax.mail.Folder)2 Multipart (javax.mail.Multipart)2 Store (javax.mail.Store)2 URLName (javax.mail.URLName)2 MailException (cn.bran.play.exceptions.MailException)1 PropertiesUtil (com.myspringboot.utils.PropertiesUtil)1 IMAPFolder (com.sun.mail.imap.IMAPFolder)1