[펌]Gmail SMTP Server를 이용한 메일전송 예제

Gmail SMTP Server를 이용한 메일전송 예제 (무료 SMTP & Authentication)

http://unionbaby.tistory.com/category/+%20Programer/*%20java?page=2

Gmail, Authentication in JavaMail

JavaMail 1.4.1:http://java.sun.com/products/javamail/downloads/index.html

JAF 1.1.1: http://java.sun.com/products/javabeans/jaf/downloads/index.html

 

Gmail.java

import javax.mail.*;

import javax.mail.internet.*;

import javax.activation.*;

import java.io.*;

import java.util.*;

import java.security.Security;

public class Gmail

{

public static void main(String[] args)

{

Properties p = new Properties();

p.put(“mail.smtp.user”, “gmail_id@gmail.com“);

p.put(“mail.smtp.host”, “smtp.gmail.com”);

p.put(“mail.smtp.port”, “465”);

p.put(“mail.smtp.starttls.enable”,”true”);

p.put( “mail.smtp.auth”, “true”);

p.put(“mail.smtp.debug”, “true”);

p.put(“mail.smtp.socketFactory.port”, “465”);

p.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);

p.put(“mail.smtp.socketFactory.fallback”, “false”);

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

try {

Authenticator auth = new SMTPAuthenticator();

Session session = Session.getInstance(p, auth);

session.setDebug(true);

//session = Session.getDefaultInstance(p);

MimeMessage msg = new MimeMessage(session);

String message = “Gmail SMTP 서버를 이용한 JavaMail 테스트”;

msg.setSubject(“Gmail SMTP 서버를 이용한 JavaMail 테스트”);

Address fromAddr = new InternetAddress(“gmail_id@gmail.com“);

msg.setFrom(fromAddr);

Address toAddr = new InternetAddress(“paran_id@paran.com“);

msg.addRecipient(Message.RecipientType.TO, toAddr);

msg.setContent(message, “text/plain;charset=KSC5601”);

System.out.println(“Message: ” + msg.getContent());

Transport.send(msg);

System.out.println(“Gmail SMTP서버를 이용한 메일보내기 성공”);

}

catch (Exception mex) { // Prints all nested (chained) exceptions as well

System.out.println(“I am here??? “);

mex.printStackTrace();

}

}

private static class SMTPAuthenticator extends javax.mail.Authenticator {

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(“cwiskykim”, “cw******”); // Google id, pwd

}

}

}

 

 

 

GoogleTest.java

import java.security.Security;

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 GoogleTest {

private static final String SMTP_HOST_NAME = “smtp.gmail.com”;

private static final String SMTP_PORT = “465”;

private static final String emailMsgTxt = “Gmail SMTP 서버를 사용한 JavaMail 테스트”;

private static final String emailSubjectTxt = “Gmail SMTP 테스트”;

private static final String emailFromAddress = “cwisky@yahoo.com“;

private static final String SSL_FACTORY = “javax.net.ssl.SSLSocketFactory”;

private static final String[] sendTo = { “cwisky@paran.com“};

 

public static void main(String args[]) throws Exception {

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt, emailMsgTxt, emailFromAddress);

System.out.println(“Sucessfully Sent mail to All Users”);

}

public void sendSSLMessage(String recipients[], String subject,

String message, String from) throws MessagingException {

boolean debug = true;

Properties props = new Properties();

props.put(“mail.smtp.host”, SMTP_HOST_NAME);

props.put(“mail.smtp.auth”, “true”);

props.put(“mail.debug”, “true”);

props.put(“mail.smtp.port”, SMTP_PORT);

props.put(“mail.smtp.socketFactory.port”, SMTP_PORT);

props.put(“mail.smtp.socketFactory.class”, SSL_FACTORY);

props.put(“mail.smtp.socketFactory.fallback”, “false”);

Session session = Session.getDefaultInstance(props,

new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(“cwiskykim“, “cw******“);

}

}

);

session.setDebug(debug);

Message msg = new MimeMessage(session);

InternetAddress addressFrom = new InternetAddress(from);

msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];

for (int i = 0; i < recipients.length; i++) {

addressTo[i] = new InternetAddress(recipients[i]);

}

msg.setRecipients(Message.RecipientType.TO, addressTo);

// Setting the Subject and Content Type

msg.setSubject(subject);

msg.setContent(message, “text/plain;charset=KSC5601”);

Transport.send(msg);

}

}

 

GMail SMTP 서버를 이용하여 텍스트와 첨부파일을 전송하는 예제 프로그램

package mail;

import java.io.File;

import java.security.Security;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class GmailSMTP {

private static final String SMTP_HOST_NAME = “smtp.gmail.com”;

private static final String SMTP_PORT = “465”;

private static final String emailMsgTxt = “Gmail SMTP 서버를 사용한 JavaMail 테스트”;

private static final String emailSubjectTxt = “Gmail SMTP 테스트”;

private static final String emailFromAddress = “cwisky@yahoo.com“;

private static final String SSL_FACTORY = “javax.net.ssl.SSLSocketFactory”;

private static final String[] sendTo = { “cwisky@paran.com“};

 

public static void main(String args[]) throws Exception {

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

new GmailSMTP().sendSSLMessage(sendTo, emailSubjectTxt, emailMsgTxt, emailFromAddress);

System.out.println(“Sucessfully Sent mail to All Users”);

}

public void sendSSLMessage(String recipients[], String subject,

String message, String from) throws MessagingException {

boolean debug = true;

Properties props = new Properties();

props.put(“mail.smtp.host”, SMTP_HOST_NAME);

props.put(“mail.smtp.auth”, “true”);

props.put(“mail.debug”, “true”);

props.put(“mail.smtp.port”, SMTP_PORT);

props.put(“mail.smtp.socketFactory.port”, SMTP_PORT);

props.put(“mail.smtp.socketFactory.class”, SSL_FACTORY);

props.put(“mail.smtp.socketFactory.fallback”, “false”);

Session session = Session.getDefaultInstance(props,

new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(“cwiskykim“, “cw123456“);

}

}

);

session.setDebug(debug);

Message msg = new MimeMessage(session);

InternetAddress addressFrom = new InternetAddress(from);

msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];

for (int i = 0; i < recipients.length; i++) {

addressTo[i] = new InternetAddress(recipients[i]);

}

msg.setRecipients(Message.RecipientType.TO, addressTo);

// Setting the Subject and Content Type

msg.setSubject(subject);

 

/*텍스트만 전송하는 경우 아래의 2라인만 추가하면 된다.

* 그러나 텍스트와 첨부파일을 함께 전송하는 경우에는 아래의 2라인을 제거하고

* 대신에 그 아래의 모든 문장을 추가해야 한다.

**/

 

//msg.setContent(message, “text/plain;charset=KSC5601”);

//Transport.send(msg);

 

/* 텍스트와 첨부파일을 함께 전송하는 경우에는 위의 2라인을 제거하고 아래의 모든 라인을 추가한다.*/

// Create the message part

BodyPart messageBodyPart = new MimeBodyPart();

 

// Fill the message

messageBodyPart.setText(“테스트용 메일의 내용입니다.”);

Multipart multipart = new MimeMultipart();

multipart.addBodyPart(messageBodyPart);

 

// Part two is attachment

messageBodyPart = new MimeBodyPart();

File file = new File(“C:/append.txt“);

FileDataSource fds = new FileDataSource(file);

messageBodyPart.setDataHandler(new DataHandler(fds));

messageBodyPart.setFileName(fds.getName());

multipart.addBodyPart(messageBodyPart);

 

// Put parts in message

msg.setContent(multipart);

 

// Send the message

Transport.send(msg);

 

System.out.println(“E-mail successfully sent!!”);

}

}

 

Gmail_POP3.java

package gmail;

/**

1.Log into your gmail account via webmail http://mail.google.com/

2.Click on “settings” and select “Mail Forwarding & POP3/IMAP”

3.Select “enable POP for all mail” and “save changes”

4.In the code below replace USERNAME & PASSWORD with your respective GMAIL account username and its corresponding password!

*/

public class Gmail_POP3 {

 

static final String USERNAME = “cwiskykim@gmail.com“;

static final String PASSWORD = “cw123456“;

 

public Gmail_POP3() {}

 

public static void main(String[] args) {

 

try {

GmailUtilities gmail = new GmailUtilities();

gmail.setUserPass(USERNAME, PASSWORD); // Gmail 계정 메일주소, 암호

gmail.connect();

gmail.openFolder(“INBOX”);

 

int totalMessages = gmail.getMessageCount();

int newMessages = gmail.getNewMessageCount();

 

System.out.println(“Total messages = ” + totalMessages);

System.out.println(“New messages = ” + newMessages);

System.out.println(“——————————-“);

 

//Uncomment the below line to print the body of the message.

//Remember it will eat-up your bandwidth if you have 100’s of messages.

//gmail.printAllMessageEnvelopes();

gmail.printAllMessages();

 

} catch(Exception e) {

e.printStackTrace();

System.exit(-1);

}

}

}

 

 

GmailUtilities.java

package gmail;

import com.sun.mail.pop3.POP3SSLStore;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.util.Date;

import java.util.Properties;

import javax.mail.Address;

import javax.mail.FetchProfile;

import javax.mail.Flags;

import javax.mail.Folder;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.Part;

import javax.mail.Session;

import javax.mail.Store;

import javax.mail.URLName;

import javax.mail.internet.ContentType;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.ParseException;

 

public class GmailUtilities {

 

private Session session = null;

private Store store = null;

private String username, password;

private Folder folder;

 

public GmailUtilities() {

 

}

 

public void setUserPass(String username, String password) {

this.username = username;

this.password = password;

}

 

public void connect() throws Exception {

 

String SSL_FACTORY = “javax.net.ssl.SSLSocketFactory”;

 

Properties pop3Props = new Properties();

 

pop3Props.setProperty(“mail.pop3.socketFactory.class”, SSL_FACTORY);

pop3Props.setProperty(“mail.pop3.socketFactory.fallback”, “false”);

pop3Props.setProperty(“mail.pop3.port”,  “995”);

pop3Props.setProperty(“mail.pop3.socketFactory.port”, “995”);

 

URLName url = new URLName(“pop3”, “pop.gmail.com”, 995, “”,

username, password);

 

session = Session.getInstance(pop3Props, null);

store = new POP3SSLStore(session, url);

store.connect();

 

}

 

public void openFolder(String folderName) throws Exception {

 

// Open the Folder

folder = store.getDefaultFolder();

 

folder = folder.getFolder(folderName);

 

if (folder == null) {

throw new Exception(“Invalid folder”);

}

 

// try to open read/write and if that fails try read-only

try {

 

folder.open(Folder.READ_WRITE);

 

} catch (MessagingException ex) {

 

folder.open(Folder.READ_ONLY);

 

}

}

 

public void closeFolder() throws Exception {

folder.close(false);

}

 

public int getMessageCount() throws Exception {

return folder.getMessageCount();

}

 

public int getNewMessageCount() throws Exception {

return folder.getNewMessageCount();

}

 

public void disconnect() throws Exception {

store.close();

}

 

public void printMessage(int messageNo) throws Exception {

System.out.println(“Getting message number: ” + messageNo);

 

Message m = null;

 

try {

m = folder.getMessage(messageNo);

dumpPart(m);

} catch (IndexOutOfBoundsException iex) {

System.out.println(“Message number out of range”);

}

}

 

public void printAllMessageEnvelopes() throws Exception {

 

// Attributes & Flags for all messages ..

Message[] msgs = folder.getMessages();

 

// Use a suitable FetchProfile

FetchProfile fp = new FetchProfile();

fp.add(FetchProfile.Item.ENVELOPE);

folder.fetch(msgs, fp);

 

for (int i = 0; i < msgs.length; i++) {

System.out.println(“————————–“);

System.out.println(“MESSAGE #” + (i + 1) + “:”);

dumpEnvelope(msgs[i]);

 

}

 

}

 

public void printAllMessages() throws Exception {

 

// Attributes & Flags for all messages ..

Message[] msgs = folder.getMessages();

 

// Use a suitable FetchProfile

FetchProfile fp = new FetchProfile();

fp.add(FetchProfile.Item.ENVELOPE);

folder.fetch(msgs, fp);

 

for (int i = 0; i < msgs.length; i++) {

System.out.println(“————————–“);

System.out.println(“MESSAGE #” + (i + 1) + “:”);

dumpPart(msgs[i]);

}

 

 

}

 

 

public static void dumpPart(Part p) throws Exception {

if (p instanceof Message)

dumpEnvelope((Message)p);

 

String ct = p.getContentType();

try {

pr(“CONTENT-TYPE: ” + (new ContentType(ct)).toString());

} catch (ParseException pex) {

pr(“BAD CONTENT-TYPE: ” + ct);

}

 

/*

* Using isMimeType to determine the content type avoids

* fetching the actual content data until we need it.

*/

if (p.isMimeType(“text/plain”)) {

pr(“This is plain text”);

pr(“—————————“);

System.out.println((String)p.getContent());

} else {

 

// just a separator

pr(“—————————“);

 

}

}

 

public static void dumpEnvelope(Message m) throws Exception {

pr(” “);

Address[] a;

// FROM

if ((a = m.getFrom()) != null) {

for (int j = 0; j < a.length; j++)

pr(“FROM: ” + a[j].toString());

}

 

// TO

if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {

for (int j = 0; j < a.length; j++) {

pr(“TO: ” + a[j].toString());

}

}

 

// SUBJECT

pr(“SUBJECT: ” + m.getSubject());

 

// DATE

Date d = m.getSentDate();

pr(“SendDate: ” +

(d != null ? d.toString() : “UNKNOWN”));

 

// CONTENT

pr(“CONTENT: “+ m.getContent());

 

}

 

static String indentStr = ”                                               “;

static int level = 0;

 

/**

* Print a, possibly indented, string.

*/

public static void pr(String s) {

 

System.out.print(indentStr.substring(0, level * 2));

System.out.println(s);

}

 

}