JavaMail 1.4
http://java.sun.com/products/javamail/index.jsp
http://java.sun.com/products/javamail/downloads/index.html
압축풀어서 mail.jar 파일을 %JAVA_HOME%\lib 아래 복사
JavaBeans Activation Framework (JAF)
http://java.sun.com/products/javabeans/jaf/index.jsp
http://java.sun.com/products/javabeans/jaf/downloads/index.html
압축풀어서 activation.jar 파일을 %JAVA_HOME%\lib 아래 복사
classpath 에 mail.jar 와 activation.jar 파일 추가
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class MailTest {
public static void main(String[] args)
throws Exception
{
String host = "SMTP서버";
String senderemail = "보내는 사람 메일 주소";
String email = "받는 사람 메일 주소";
String subject = "제목";
String mailtext = "<html><body><h1>내용</h1></body></html>";
String[] attached = {"D:/projects/encyclopedia/java/mail/석양.jpg", "D:/projects/encyclopedia/java/mail/겨울.jpg"};
sendEmail(host, senderemail, email, subject, mailtext, attached);
}
/**
* send Email.
*
* @param host 메일서버주소
* @param from 보내는 사람
* @param to 받는사람 - ","로 구분된 메일 주소
* @param subject 제목
* @param mailtext 내용
* @param attached 첨부파일
* @result boolean
* @exception javax.mail.internet.AddressException
* javax.mail.MessagingException
*/
public static void sendEmail(String host, String senderemail, String email,
String subject,String mailtext, String[] attached)
throws javax.mail.internet.AddressException, javax.mail.MessagingException,
java.io.UnsupportedEncodingException
{
Properties props = new Properties();
props.put("mail.smtp.host", host);
Session session = Session.getDefaultInstance(props, null);
Multipart mp = new MimeMultipart();
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(senderemail));
// 받는사람
InternetAddress[] toAddress = InternetAddress.parse(email);
msg.setRecipients(Message.RecipientType.TO, toAddress);
// 제목
msg.setSubject(subject, "euc-kr");
// 내용
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(mailtext, "text/html; charset=euc-kr");
mp.addBodyPart(mbp1);
System.out.println("host="+host);
System.out.println("sender="+senderemail);
System.out.println("receive="+email);
System.out.println("mbp1="+mbp1);
// 파일첨부
if (attached != null) {
for (int i = 0; i < attached.length; i++) {
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(attached[i]);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(iso8859(fds.getName()));
mp.addBodyPart(mbp2);
}
}
// 메시지 add
msg.setContent(mp);
// header 에 날짜 삽입
msg.setSentDate(new Date());
// send the message
Transport.send(msg);
}
public static String iso8859(String strStr)
throws java.io.UnsupportedEncodingException
{
if (strStr == null)
{
return null;
}
else
{
return new String(strStr.getBytes("KSC5601"), "8859_1");
}
}
}
[출처] [JAVA] Java Mail 보내기|작성자 소토로