수색…


비고

Oracle 웹 사이트의 JavaMail 페이지는 다음과 같이 설명합니다

JavaMail API는 메일 및 메시징 응용 프로그램을 빌드하기위한 플랫폼 독립적이며 프로토콜 독립 프레임 워크를 제공합니다. JavaMail API는 Java SE 플랫폼과 함께 사용할 수있는 선택적 패키지로 사용할 수 있으며 Java EE 플랫폼에도 포함되어 있습니다.

JavaMail 프로젝트의 기본 사이트는 이제 java.net에 있습니다. 여기에서 여러 버전의 API에 대한 javadoc, 소스 코드 저장소에 대한 링크, 다운로드 링크, JavaMail을 널리 사용되는 전자 메일 서비스 공급자와 함께 사용하기위한 힌트 등을 찾을 수 있습니다.

POP3 전자 메일 서버로 전자 메일 보내기

이 예에서는 SSL 사용 POP3 전자 메일 서버에 대한 연결을 설정하고 간단한 (텍스트 전용) 전자 메일을 보내는 방법을 보여줍니다.

    // Configure mail provider
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.mymailprovider.com");
    props.put("mail.pop3.host", "pop3.mymailprovider.com");
    // Enable SSL
    props.put("mail.pop3.ssl.enable", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // Enable SMTP Authentication
    props.put("mail.smtp.auth","true");

    Authenticator auth = new PasswordAuthentication("user", "password");
    Session session = Session.getDefaultInstance(props, auth);

    // Get the store for authentication
    final Store store;
    try {
        store = session.getStore("pop3");
    } catch (NoSuchProviderException e) {
        throw new IllegalStateException(e);
    }

    try {
        store.connect();
    } catch (AuthenticationFailedException | MessagingException e) {
        throw new IllegalStateException(e);
    }
    
    try {
      // Setting up the mail
      InternetAddress from = new InternetAddress("[email protected]");
      InternetAddress to = new InternetAddress("[email protected]");

      MimeMessage message = new MimeMessage(session);
      message.setFrom(from);
      message.addRecipient(Message.RecipientType.TO, to);

      message.setSubject("Test Subject");
      message.setText("Hi, I'm a Mail sent with Java Mail API.");

      // Send the mail
      Transport.send(message);
    } catch (AddressException | MessagingException e)
        throw new IllegalStateException(e);
    } 

주의 사항 :

  • 다양한 세부 사항이 위의 코드에 설명을 위해 하드 와이어되어 있습니다.
  • 예외 처리는 예외가 아닙니다. IllegalStateException 은 잘못된 선택입니다.
  • 리소스를 올바르게 처리하려고 시도하지 않았습니다.

간단한 이메일 보내기

public class GoogleMailTest {

    GoogleMailTest() {

    }

    public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
        GoogleMailTest.Send(username, password, recipientEmail, "", title, message);
    }

    public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.put("mail.debug", "true");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");
        props.put("mail.smtps.quitwait", "false");
        Session session = Session.getInstance(props, null);
        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
        JOptionPane.showMessageDialog(null, msg.getSize());
        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }
        msg.setSubject(title);
        msg.setText(message);
        msg.setSentDate(new Date());
        SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
        t.connect("smtp.gmail.com", username, password);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    }
    //    And use this code in any class, I'm using it in the same class in main method
    public static void main(String[] args) {
        String senderMail = "[email protected]"; //sender mail id
        String password = "769inzimam-9771"; // sender mail password here
        String toMail = "[email protected]"; // recepient  mail id here
        String cc = ""; // cc mail id here
        String title = "Java mail test"; // Subject of the mail
        String msg = "Message here"; // message to be sent

        GoogleMailTest gmt = new GoogleMailTest();

        try {
            if (cc.isEmpty()) {
                GoogleMailTest.Send(senderMail, password, toMail, title, msg);
            } else {
                GoogleMailTest.Send(senderMail, password, toMail, cc, title, msg);
            }
        } catch (MessagingException ex) {
            Logger.getLogger(GoogleMailTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

HTML 형식의 메일 보내기

약간의 수정을 가한 Simple Mail Send 와 동일한 예를 사용할 수 있습니다. msg.setContent() 대신 msg.setText() 를 사용하고 콘텐츠 유형 htmltext/html .

이것을 확인하십시오.

msg.setContent(message, "text/html; charset=utf-8");

대신에

msg.setText(message);


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow