'Email'에 해당되는 글 1건

  1. GMail을 통해서 메일보내기.. 2009/10/19
GMail의 ID/PW만 있으면 메일을 쉽게 보낼 수가 있네요. ^^
아래는 http://www.easemarry.com/blog/java-use-gmail-account-to-send-mail/ 의 코드를 제가 사용하기 위해서 살짝 바꿨습니다. ^^

package net.sjava.email.test;

import java.security.Security;
import java.util.Date;
import java.util.Properties;  
 
import javax.mail.Authenticator;
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 GMailSenderTest {

    private static final String SSLFACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String USERID = "id@gmail.com";
    private static final String PASSWORD = "pw";
    private static Properties properties = System.getProperties();
   
    static {
        properties.setProperty("mail.smtp.host", "smtp.gmail.com");
        properties.setProperty("mail.smtp.socketFactory.class", SSLFACTORY);
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.auth", "true");
    }
   
    //
    public Message getMessage(Session session, String to, String title, String content) throws MessagingException {
        Message msg = new MimeMessage(session);     
        msg.setFrom(new InternetAddress(to));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        msg.setSubject(title);
        msg.setText(content);
        msg.setSentDate(new Date());
        
        return msg;
    }
   
    //
    public void send(String to, String title, String content) {
        
        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());            
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USERID, PASSWORD);
                }
            });            
            Transport.send(this.getMessage(session, to, title, content));
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        GMailSenderTest sender = new GMailSenderTest();
        sender.send("skidboy@daum.net", "헐", "내용");
    }
}



Tag // , ,