import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import com.srpost.salmon.lang.StringUtil;
public class SMTPMailSend {
public static void mailSend(List<String> toMails, String fromMail, String fromName,
String contents, String title, String mailId,
String mailPwd) throws MessagingException, UnsupportedEncodingException {
if (StringUtil.isEmpty(mailPwd)) {
// 내 메일 Access 허용 비밀번호,
mailPwd = "구글에서 발급받은 16자리"; (gmail 로그인 비밀번호 아님)
}
Properties props = new Properties();
props.put("mail.smtp.user", "내 Gmail 주소"); // "user@gmail.com"
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Authenticator auth = new SMTPAuthenticator(mailId, mailPwd);
Session mailSession = Session.getInstance(props, auth);
mailSession.setDebug(true); // 메일 전송할 때 상세한 상황을 콘솔에 출력한다.
Address fromMailAddress = null;
if (StringUtil.isEmpty(fromName)) { // 메일 보낸사람이름 등록시
fromMailAddress = new InternetAddress(fromMail);
}
else { // 메일 보낸사람이름 미등록시
fromMailAddress = new InternetAddress(fromMail, MimeUtility.encodeText(fromName, "UTF-8", "B"));
}
MimeMessage mailMsg = new MimeMessage(mailSession);
mailMsg.setFrom(fromMailAddress);
mailMsg.setSubject(title, "UTF-8");
InternetAddress[] toMailAddress = new InternetAddress[toMails.size()];
for (int i = 0; i < toMails.size(); i++) {
toMailAddress[i] = new InternetAddress(toMails.get(i));
}
mailMsg.setRecipients(Message.RecipientType.TO, toMailAddress);
mailMsg.setContent(contents, "text/html;charset=utf-8");
// 전송
Transport.send(mailMsg);
}
}
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class SMTPAuthenticator extends Authenticator {
private String mailId;
private String mailPwd;
public SMTPAuthenticator(String mailId, String mailPwd) {
this.mailId = mailId;
this.mailPwd = mailPwd;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailId, mailPwd);
}
}
'공부 > JAVA' 카테고리의 다른 글
JAVA_[Google URL Shortener API] (0) | 2017.11.22 |
---|---|
JAVA_[ Collection.srot (리스트 정렬)] (0) | 2015.03.26 |
JAVA_[ 제어자 ] (0) | 2015.02.10 |
JAVA_[ JVM의 메모리구조 ] (0) | 2015.02.10 |
JAVA_[Thread join()] (0) | 2015.02.09 |