[java] Javamail을 사용하여 이메일에 일정 추가하기

Javamail은 Java 프로그램에서 이메일을 송신하고 수신하기 위한 라이브러리입니다. 이 블로그 포스트에서는 Javamail을 사용하여 이메일에 일정을 추가하는 방법에 대해 알아보겠습니다.

1. Javamail 라이브러리 추가

Javamail을 사용하기 위해서는 먼저 해당 라이브러리를 프로젝트에 추가해야 합니다. 아래 Maven 의존성을 pom.xml 파일에 추가하거나 해당 JAR 파일을 프로젝트에 직접 추가할 수 있습니다.

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.6.2</version>
</dependency>

2. 이메일 서버 정보 설정

이메일을 보내기 위해 사용할 이메일 서버의 정보를 설정해야 합니다. 예를 들어 SMTP(Simple Mail Transfer Protocol) 서버를 사용한다면, 아래와 같이 설정할 수 있습니다.

String host = "smtp.example.com";
String username = "your-email@example.com";
String password = "your-password";
int port = 587;

Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.port", port);

Session session = Session.getInstance(properties, new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
});

3. 이메일에 일정 추가

이제 Javamail을 사용하여 이메일에 일정을 추가해보겠습니다. 아래와 같이 MimeMessage 객체를 생성한 후, 이메일의 제목, 내용, 수신자, 발신자 등을 설정할 수 있습니다.

MimeMessage message = new MimeMessage(session);

message.setFrom(new InternetAddress(username));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
message.setSubject("Meeting Reminder: Weekly Team Meeting");
message.setText("Dear team, \n\nThis is a reminder for our weekly team meeting scheduled for tomorrow at 10 AM. Please make sure to attend.\n\nBest regards, \nJohn");

// 일정 추가
Multipart multipart = new MimeMultipart();
DateTime startDateTime = // 일정 시작 시간
DateTime endDateTime = // 일정 종료 시간
String location = "Conference Room"; // 일정 장소

// 일정이 들어갈 콘텐츠
String calendarContent = "BEGIN:VCALENDAR\n" +
        "VERSION:2.0\n" +
        "PRODID:-//Example Corp//CalDAV Client//EN\n" +
        "METHOD:PUBLISH\n" +
        "BEGIN:VEVENT\n" +
        "DTSTAMP:" + startDateTime + "\n" +
        "DTSTART:" + startDateTime + "\n" +
        "DTEND:" + endDateTime + "\n" +
        "SUMMARY:Weekly Team Meeting\n" +
        "LOCATION:" + location + "\n" +
        "END:VEVENT\n" +
        "END:VCALENDAR";

// 일정 콘텐츠를 MimeBodyPart에 추가
MimeBodyPart calendarPart = new MimeBodyPart();
calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL");

multipart.addBodyPart(calendarPart);
message.setContent(multipart);

// 이메일 전송
Transport.send(message);

위의 예제 코드에서는 MultipartMimeBodyPart를 사용하여 일정을 추가하고, Transport.send() 메소드를 통해 이메일을 전송합니다.

마치며

위의 예제 코드를 사용하여 Javamail을 사용하여 이메일에 일정을 쉽게 추가할 수 있습니다. Javamail은 다양한 기능을 제공하므로 프로젝트의 요구에 맞게 활용할 수 있습니다.

더 자세한 내용은 Javamail 공식 문서를 참조하시기 바랍니다.