java.util.Properties 와 javax.mail 패키지를 이용하여 여러 사람에게 메일을 보내보자.
구글 gmail 인증을 위한 Class
1 2 3 4 5 6 7 8 9 10 11 12
| public class MailAuthenticator extends Authenticator { private String id; private String pw;
public MailAuthenticator(String id, String pw){ this.id = id; this.pw = pw; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(id, pw); } }
|
구글 gmail 발송 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| public class MailUtil { private String user = "test@gmail.com"; private String passwd = "test"; private Session mailSession; private Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.auth", "true"); props.setProperty("mail.smtp.starttls.enable", "true"); props.setProperty("mail.smtp.port", "587"); public boolean sendMail(List<InternetAddress> to, String subject, StringBuffer content) { if(to == null || to.size() == 0) { return false; } Authenticator authenticator = new MailAuthenticator(user, passwd); mailSession = Session.getDefaultInstance(props, authenticator); MimeMessage msg = new MimeMessage(mailSession); InternetAddress from = new InternetAddress(); String fromName = "발신자 닉네임"; from = new InternetAddress(new String(fromName.getBytes(charSet), "8859_1") + "<발신자 구글 이메일@gmail.com>"); msg.setFrom(from); InternetAddress[] address = new InternetAddress[to.size()];
for (int i = 0; i < to.size(); i++) { address[i] = to.get(i); } msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject, "UTF-8"); msg.setContent(content.toString(), "text/html; charset=UTF-8"); msg.setSentDate(new java.util.Date()); Transport.send(msg); return true; } }
|