지메일(GMail)을 사용해서 메일을 보내는 예제이다.
package net.sjava.email.test; import java.security.Security; 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”, “헐”, “내용”); } }