The Pursuit of Happyness

반응형


import java.util.Properties;


import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;


public class GmailSMTP

{

    public static void sendMail(String account, String auth, String to, String subject, String msg, boolean isSSL, boolean isHtml)

    {

        final String username = account;

        final String password = auth;


        String mailFrom = username;

        String mailTo = to;


        Properties props = new Properties();

        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.host", "smtp.gmail.com");


        if (isSSL)

        {

            props.put("mail.smtp.socketFactory.port", "465");

            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

            props.put("mail.smtp.port", "465");

        }

        else

        {

            props.put("mail.smtp.starttls.enable", "true");

            props.put("mail.smtp.port", "587");

        }


        Session session = Session.getInstance(props, new javax.mail.Authenticator()

        {

            protected PasswordAuthentication getPasswordAuthentication()

            {

                return new PasswordAuthentication(username, password);

            }

        });


        try

        {

            Message message = new MimeMessage(session);

            message.setFrom(new InternetAddress(mailFrom));

            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo));

            message.setSubject(subject);


            if (isHtml)

                message.setContent(msg, "text/html");

            else

                message.setText(msg);


            Transport.send(message);

        }

        catch (MessagingException e)

        {

            throw new RuntimeException(e);

        }

    }

}

 


ps. mail.jar 가 필요함


반응형