자바를 사용하여 이메일 보내기


112

Java를 사용하여 이메일을 보내려고합니다.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail {

   public static void main(String [] args) {

      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

오류가 발생합니다.

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is:java.net.ConnectException: Connection refused: connect
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)

이 코드가 이메일을 보내는 데 작동합니까?


11
포트 25에서 수신 대기하는 동일한 시스템에서 SMTP 서버를 실행하고 있습니까?
제프

주소로 Gmail을 통해 릴레이하려고한다고 가정하겠습니다. 이것이 사실이라면 사용할 수있는 코드가있을 수 있습니다. 여기에 힌트가 있습니다. TLS가 필요합니다.
Paul Gregoire

@Mondain 5 개의 코드를 작성할 수 있다면 도움이 될 것입니다. Gmail을 사용하여 릴레이하고 싶습니다
Mohit Bansal

아래의 내 대답에 링크되어 있지만 유일한 문제는 JavaMail 라이브러리를 사용하지 않는다는 것입니다. 원하시면 전체 소스를 보내드릴 수 있습니다.
Paul Gregoire

답변:


98

다음 코드는 Google SMTP 서버에서 매우 잘 작동합니다. Google 사용자 이름과 비밀번호를 제공해야합니다.

import com.sun.mail.smtp.SMTPTransport;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author doraemon
 */
public class GoogleMail {
    private GoogleMail() {
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param title title of the message
     * @param message message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
        GoogleMail.Send(username, password, recipientEmail, "", title, message);
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param ccEmail CC recipient. Can be empty if there is no CC recipient
     * @param title title of the message
     * @param message message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    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.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");

        /*
        If set to false, the QUIT command is sent and the connection is immediately closed. If set 
        to true (the default), causes the transport to wait for the response to the QUIT command.

        ref :   http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
                http://forum.java.sun.com/thread.jspa?threadID=5205249
                smtpsend.java - demo program from javamail
        */
        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 + "@gmail.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }

        msg.setSubject(title);
        msg.setText(message, "utf-8");
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

        t.connect("smtp.gmail.com", username, password);
        t.sendMessage(msg, msg.getAllRecipients());      
        t.close();
    }
}

2015 년 12 월 11 일 업데이트

사용자 이름 + 암호는 더 이상 권장되는 솔루션이 아닙니다. 이것은 ~ 때문이다

이를 시도한 결과 Gmail은이 코드에서 사용자 이름으로 사용 된 이메일에 최근에 귀하의 Google 계정에 대한 로그인 시도를 차단하고 다음 지원 페이지로 연결되었다는 이메일을 보냈습니다. support.google.com/accounts/answer/6010255 그래서 그것이 작동하는지 확인하고, 보내는 데 사용되는 이메일 계정은 자체 보안을 줄여야합니다.

Google은 Gmail API ( https://developers.google.com/gmail/api/?hl=en)를 출시했습니다 . 사용자 이름 + 비밀번호 대신 oAuth2 방법을 사용해야합니다.

다음은 Gmail API와 함께 작동하는 코드 스 니펫입니다.

GoogleMail.java

import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author doraemon
 */
public class GoogleMail {
    private GoogleMail() {
    }

    private static MimeMessage createEmail(String to, String cc, String from, String subject, String bodyText) throws MessagingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session);
        InternetAddress tAddress = new InternetAddress(to);
        InternetAddress cAddress = cc.isEmpty() ? null : new InternetAddress(cc);
        InternetAddress fAddress = new InternetAddress(from);

        email.setFrom(fAddress);
        if (cAddress != null) {
            email.addRecipient(javax.mail.Message.RecipientType.CC, cAddress);
        }
        email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
        email.setSubject(subject);
        email.setText(bodyText);
        return email;
    }

    private static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
    }

    public static void Send(Gmail service, String recipientEmail, String ccEmail, String fromEmail, String title, String message) throws IOException, MessagingException {
        Message m = createMessageWithEmail(createEmail(recipientEmail, ccEmail, fromEmail, title, message));
        service.users().messages().send("me", m).execute();
    }
}

oAuth2를 통해 승인 된 Gmail 서비스를 구성하려면 다음 코드를 참조하세요.

Utils.java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.oauth2.Oauth2;
import com.google.api.services.oauth2.model.Userinfoplus;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.yccheok.jstock.engine.Pair;

/**
 *
 * @author yccheok
 */
public class Utils {
    /** Global instance of the JSON factory. */
    private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport httpTransport;

    private static final Log log = LogFactory.getLog(Utils.class);

    static {
        try {
            // initialize the transport
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        } catch (IOException ex) {
            log.error(null, ex);
        } catch (GeneralSecurityException ex) {
            log.error(null, ex);
        }
    }

    private static File getGmailDataDirectory() {
        return new File(org.yccheok.jstock.gui.Utils.getUserDataDirectory() + "authentication" + File.separator + "gmail");
    }

    /**
     * Send a request to the UserInfo API to retrieve the user's information.
     *
     * @param credentials OAuth 2.0 credentials to authorize the request.
     * @return User's information.
     * @throws java.io.IOException
     */
    public static Userinfoplus getUserInfo(Credential credentials) throws IOException
    {
        Oauth2 userInfoService =
            new Oauth2.Builder(httpTransport, JSON_FACTORY, credentials).setApplicationName("JStock").build();
        Userinfoplus userInfo  = userInfoService.userinfo().get().execute();
        return userInfo;
    }

    public static String loadEmail(File dataStoreDirectory)  {
        File file = new File(dataStoreDirectory, "email");
        try {
            return new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8");
        } catch (IOException ex) {
            log.error(null, ex);
            return null;
        }
    }

    public static boolean saveEmail(File dataStoreDirectory, String email) {
        File file = new File(dataStoreDirectory, "email");
        try {
            //If the constructor throws an exception, the finally block will NOT execute
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            try {
                writer.write(email);
            } finally {
                writer.close();
            }
            return true;
        } catch (IOException ex){
            log.error(null, ex);
            return false;
        }
    }

    public static void logoutGmail() {
        File credential = new File(getGmailDataDirectory(), "StoredCredential");
        File email = new File(getGmailDataDirectory(), "email");
        credential.delete();
        email.delete();
    }

    public static Pair<Pair<Credential, String>, Boolean> authorizeGmail() throws Exception {
        // Ask for only the permissions you need. Asking for more permissions will
        // reduce the number of users who finish the process for giving you access
        // to their accounts. It will also increase the amount of effort you will
        // have to spend explaining to users what you are doing with their data.
        // Here we are listing all of the available scopes. You should remove scopes
        // that you are not actually using.
        Set<String> scopes = new HashSet<>();

        // We would like to display what email this credential associated to.
        scopes.add("email");

        scopes.add(GmailScopes.GMAIL_SEND);

        // load client secrets
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY,
            new InputStreamReader(Utils.class.getResourceAsStream("/assets/authentication/gmail/client_secrets.json")));

        return authorize(clientSecrets, scopes, getGmailDataDirectory());
    }

    /** Authorizes the installed application to access user's protected data.
     * @return 
     * @throws java.lang.Exception */
    private static Pair<Pair<Credential, String>, Boolean> authorize(GoogleClientSecrets clientSecrets, Set<String> scopes, File dataStoreDirectory) throws Exception {
        // Set up authorization code flow.

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, JSON_FACTORY, clientSecrets, scopes)
            .setDataStoreFactory(new FileDataStoreFactory(dataStoreDirectory))
            .build();
        // authorize
        return new MyAuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

    public static Gmail getGmail(Credential credential) {
        Gmail service = new Gmail.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("JStock").build();
        return service;        
    }
}

사용자 친화적 인 oAuth2 인증 방법을 제공하기 위해 JavaFX를 사용하여 다음 입력 대화 상자를 표시했습니다.

여기에 이미지 설명 입력

사용자 친화적 인 oAuth2 대화 상자를 표시하는 키는 MyAuthorizationCodeInstalledApp.javaSimpleSwingBrowser.java 에서 찾을 수 있습니다.


오류 발생 : "main"스레드에서 예외 javax.mail.MessagingException : SMTP 호스트에 연결할 수 없음 : smtp.gmail.com, 포트 : 465; 중첩 된 예외 : java.net.ConnectException : 연결 시간 초과 : com.sun.mail.smtp.SMTPTransport.openServer (SMTPTransport.java:1706)에서 연결
Mohit Bansal

1
smtp.gmail.com을 핑하면 응답이 있습니까?
Cheok Yan Cheng

내가 STMP를 처음 사용하기 전에 말했듯이 smtp.gmail.com에 핑하는 방법을 모릅니다.
Mohit Bansal

2
명령 프롬프트에서 'ping smtp.gmail.com'을 입력하고 Enter 키를 누릅니다.
Cheok Yan Cheng

12
Send대신 메서드가 호출되는 것이 마음에 들지 않지만 send유용한 클래스입니다. gmail 비밀번호를 코드에 저장하는 것이 보안에 미치는 영향에 대해 생각하십니까?
Simon Forsberg

48

다음 코드는 나를 위해 일했습니다.

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendMail {

    public static void main(String[] args) {

        final String username = "your_user_name@gmail.com";
        final String password = "yourpassword";

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

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

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("your_user_name@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("to_email_address@domain.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

1
2 단계 인증이 비활성화 된 계정에서 작업했습니다. 이 솔루션은 로컬이고 썬 패키지가 필요하지 않기 때문에 훌륭합니다.
AlikElzin-kilaka 2014

이 코드를 사용하려면 보낼 이메일이 Gmail 계정이어야합니까?
Erick

3
코드는 나를 위해 일하지만 먼저 내가 할 필요가 이것을 하고 "보안 수준이 낮은 앱의 액세스"를 켭니다

@ user4966430 동의합니다! 그리고 감사합니다!
raikumardipak

17
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendEmail extends Object{

public static void main(String [] args)
{

    try{

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.mail.yahoo.com"); // for gmail use smtp.gmail.com
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true"); 
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("username@yahoo.com", "password");
            }
        });

        mailSession.setDebug(true); // Enable the debug mode

        Message msg = new MimeMessage( mailSession );

        //--[ Set the FROM, TO, DATE and SUBJECT fields
        msg.setFrom( new InternetAddress( "fromusername@yahoo.com" ) );
        msg.setRecipients( Message.RecipientType.TO,InternetAddress.parse("tousername@gmail.com") );
        msg.setSentDate( new Date());
        msg.setSubject( "Hello World!" );

        //--[ Create the body of the mail
        msg.setText( "Hello from my first e-mail sent with JavaMail" );

        //--[ Ask the Transport class to send our mail message
        Transport.send( msg );

    }catch(Exception E){
        System.out.println( "Oops something has gone pearshaped!");
        System.out.println( E );
    }
}
}

필수 jar 파일

여기를 클릭하십시오-외부 항아리를 추가하는 방법


11

짧은 대답-아니요.

긴 대답은 아니오입니다. 코드는 로컬 컴퓨터에서 실행되고 포트 25에서 수신 대기하는 SMTP 서버의 존재에 의존하기 때문입니다. SMTP 서버 (기술적으로 MTA 또는 메일 전송 에이전트)는 메일 사용자 에이전트와의 통신을 담당합니다. (이 경우 Java 프로세스 인 MUA) 발신 이메일을 수신합니다.

이제 MTA는 일반적으로 특정 도메인의 사용자로부터 메일을 수신합니다. 따라서 gmail.com 도메인의 경우 메일 사용자 에이전트를 인증하고 따라서 Gmail 서버의받은 편지함으로 메일을 전송하는 역할을하는 것은 Google 메일 서버입니다. Gmail이 개방형 메일 릴레이 서버를 신뢰하는지 확실하지 않지만 Google을 대신하여 인증을 수행 한 다음 메일을 Gmail 서버로 릴레이하는 것은 쉬운 일이 아닙니다.

JavaMail을 사용하여 GMail에 액세스하는 방법에 대한 JavaMail FAQ 를 읽으면 호스트 이름과 포트가 확실히 localhost가 아닌 GMail 서버를 가리키는 것을 알 수 있습니다. 로컬 컴퓨터를 사용하려는 경우 릴레이 또는 전달을 수행해야합니다.

SMTP와 관련하여 어디서든 얻으려면 SMTP 프로토콜을 깊이 이해해야 할 것입니다. SMTP에 대한 Wikipedia 기사로 시작할 수 있지만, 더 진행하려면 실제로 SMTP 서버에 대한 프로그래밍이 필요합니다.


내 SMTP 서버로 Tomcat을 사용할 수 있습니까? 같은 것에 관한 도움을 주시면 감사하겠습니다. :)
CᴴᴀZ

3
@ChaZ Tomcat이 SMTP 서버가 될 것이라는 아이디어를 어디서 얻었습니까?
eis

6

메일을 보내려면 SMTP 서버가 필요합니다. 자신의 PC에 로컬로 설치할 수있는 서버가 있거나 여러 온라인 서버 중 하나를 사용할 수 있습니다. 가장 잘 알려진 서버 중 하나는 Google입니다.

Simple Java Mail 의 첫 번째 예제를 사용하여 허용 된 Google SMTP 구성 을 성공적으로 테스트했습니다 .

    final Email email = EmailBuilder.startingBlank()
        .from("lollypop", "lol.pop@somemail.com")
        .to("C.Cane", "candycane@candyshop.org")
        .withPlainText("We should meet up!")
        .withHTMLText("<b>We should meet up!</b>")
        .withSubject("hey");

    // starting 5.0.0 do the following using the MailerBuilder instead...
    new Mailer("smtp.gmail.com", 25, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
    new Mailer("smtp.gmail.com", 587, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
    new Mailer("smtp.gmail.com", 465, "your user", "your password", TransportStrategy.SMTP_SSL).sendMail(email);

다양한 포트 및 전송 전략 (필요한 모든 속성을 처리 함)에 주목하십시오.

흥미롭게도 Google의 지침에 달리 명시되어 있지만 Google은 포트 25에서도 TLS를 요구합니다 .


1
이름이 알려줍니다, 그것은 간단합니다
카이 왕

4

이것이 게시 된 지 꽤 오래되었습니다. 하지만 2012 년 11 월 13 일부로 포트 465가 여전히 작동하는지 확인할 수 있습니다.

이 포럼 에서 GaryM의 답변을 참조하십시오 . 나는 이것이 더 많은 사람들에게 도움이되기를 바랍니다.

/*
* Created on Feb 21, 2005
*
*/

import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GoogleTest {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailMsgTxt = "Test Message Contents";
    private static final String emailSubjectTxt = "A test from gmail";
    private static final String emailFromAddress = "";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String[] sendTo = { "" };


    public static void main(String args[]) throws Exception {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
            emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully mail to All Users");
    }

    public void sendSSLMessage(String recipients[], String subject,
                               String message, String from) throws MessagingException {
        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("xxxxxx", "xxxxxx");
            }
        });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }
}

1
이 링크가 질문에 답할 수 있지만 여기에 답변의 필수 부분을 포함하고 참조 용 링크를 제공하는 것이 좋습니다. 링크 된 페이지가 변경되면 링크 전용 답변이 무효화 될 수 있습니다. - 리뷰에서
swiftBoy

1
게시물의 답변을 추가했습니다.
Mukus

1
트윗 담아 가기 그것은 미래에 누군가를 도울 것입니다.
swiftBoy

3

다음 코드는 매우 잘 작동합니다. javamail-1.4.5.jar을 사용하여 자바 애플리케이션으로 사용해보세요.

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class MailSender
{
    final String senderEmailID = "typesendermailid@gmail.com";
    final String senderPassword = "typesenderpassword";
    final String emailSMTPserver = "smtp.gmail.com";
    final String emailServerPort = "465";
    String receiverEmailID = null;
    static String emailSubject = "Test Mail";
    static String emailBody = ":)";

    public MailSender(
            String receiverEmailID,
            String emailSubject,
            String emailBody
    ) {
        this.receiverEmailID=receiverEmailID;
        this.emailSubject=emailSubject;
        this.emailBody=emailBody;
        Properties props = new Properties();
        props.put("mail.smtp.user",senderEmailID);
        props.put("mail.smtp.host", emailSMTPserver);
        props.put("mail.smtp.port", emailServerPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", emailServerPort);
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        SecurityManager security = System.getSecurityManager();
        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(emailBody);
            msg.setSubject(emailSubject);
            msg.setFrom(new InternetAddress(senderEmailID));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiverEmailID));
            Transport.send(msg);
            System.out.println("Message send Successfully:)");
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
        }
    }

    public class SMTPAuthenticator extends javax.mail.Authenticator
    {
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(senderEmailID, senderPassword);
        }
    }

    public static void main(String[] args)
    {
        MailSender mailSender=new
            MailSender("typereceivermailid@gmail.com",emailSubject,emailBody);
    }
}

2

이 코드가 이메일을 보내는 데 작동합니까?

글쎄, 아니, 오류가 발생했기 때문에 일부 부품을 변경하지 않고서는 안됩니다. 현재 localhost에서 실행되는 SMTP 서버를 통해 메일을 보내려고하지만 ConnectException.

코드가 정상이라고 가정하면 (실제로 확인하지 않음) 로컬 SMTP 서버를 실행하거나 ISP에서 제공하는 원격 SMTP 서버를 사용해야합니다.

코드와 관련하여 FAQ에 언급 된 JavaMail 다운로드 패키지에서 샘플을 찾을 수 있습니다 .

JavaMail 사용 방법을 보여주는 몇 가지 예제 프로그램은 어디에서 찾을 수 있습니까?

Q : JavaMail 사용 방법을 보여주는 몇 가지 예제 프로그램은 어디에서 찾을 수 있습니까?
A : JavaMail API의 다양한 측면을 보여주는 간단한 명령 줄 프로그램, Swing 기반 GUI 응용 프로그램, 간단한 서블릿 기반 응용 프로그램, JSP 페이지를 사용하는 완전한 웹 응용 프로그램 등 JavaMail 다운로드 패키지 에 포함 된 여러 예제 프로그램 태그 라이브러리.


안녕하세요, 실제로 smtp 서버는 무엇입니까? 이메일 서버에 포함되어 번들로 제공됩니까? 아니면 smtp를 별도로 설정해야합니까?
GMsoF

dovecot은 SMTP 서버입니다. 자신에게이 질문을 질문 : 어떤 소프트웨어를이 전자 메일을 보내는 것을 구글 실행하지 에를 ? 그들은 일종의 smtp 서버를 실행하고 있습니다. Dovecot은 좋습니다. dovecot과 postfix를 함께 사용하는 것이 좋습니다. postfix는 smtp 부분이고 dovecot은 imap 부분이라고 생각합니다.
Thufir

2

이것을 시도하십시오. 그것은 나를 위해 잘 작동합니다. 이메일을 보내기 전에 Gmail 계정에서 보안 수준이 낮은 앱에 대한 액세스 권한을 부여해야합니다. 따라서 다음 링크로 이동하여이 Java 코드를 사용해보십시오.
보안 수준이 낮은 앱을 위해 Gmail 활성화

javax.mail.jar 파일과 activation.jar 파일을 프로젝트로 가져와야합니다.

이것은 자바로 이메일을 보내기위한 전체 코드입니다.

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmail {

    final String senderEmail = "your email address";
    final String senderPassword = "your password";
    final String emailSMTPserver = "smtp.gmail.com";
    final String emailServerPort = "587";
    String receiverEmail = null;
    String emailSubject = null;
    String emailBody = null;

    public SendEmail(String receiverEmail, String Subject, String message) {
        this.receiverEmail = receiverEmail;
        this.emailSubject = Subject;
        this.emailBody = message;

        Properties props = new Properties();
        props.put("mail.smtp.user", senderEmail);
        props.put("mail.smtp.host", emailSMTPserver);
        props.put("mail.smtp.port", emailServerPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", emailServerPort);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        SecurityManager security = System.getSecurityManager();

        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);

            Message msg = new MimeMessage(session);
            msg.setText(emailBody);
            msg.setSubject(emailSubject);
            msg.setFrom(new InternetAddress(senderEmail));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiverEmail));
            Transport.send(msg);
            System.out.println("send successfully");
        } catch (Exception ex) {
            System.err.println("Error occurred while sending.!");
        }

    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(senderEmail, senderPassword);
        }
    }

    public static void main(String[] args) {
        SendEmail send = new SendEmail("receiver email address", "subject", "message");
    }

}

2

여기에 작업 솔루션 형제가 있습니다. 보장됩니다.

  1. 먼저 메일을 보내려는 Gmail 계정을여십시오. xyz@gmail.com
  2. 아래 링크를 엽니 다.

    https://support.google.com/accounts/answer/6010255?hl=ko

  3. "내 계정의"보안 수준이 낮은 앱 "섹션으로 이동"을 클릭하십시오. 선택권
  4. 그런 다음 켜십시오
  5. 그게 다입니다 (:

내 코드는 다음과 같습니다.

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmail {

   final String senderEmailID = "Sender Email id";
final String senderPassword = "Sender Pass word";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
static String emailSubject = "Test Mail";
static String emailBody = ":)";
public SendEmail(String receiverEmailID, String emailSubject, String emailBody)
{
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;
Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
System.out.println("Message send Successfully:)");
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
    public static void main(String[] args) {
       SendEmail mailSender;
        mailSender = new SendEmail("Receiver Email id","Testing Code 2 example","Testing Code Body yess");
    }

}

감사! 그것은 나를 위해 일했습니다! . 나는 "내 계정에"보안 수준이 낮은 응용 프로그램 "에 가서 옵션 및 사용에 MyApp를위한 암호를 생성합니다.
raikumardipak

1

검토를 위해 작업중인 gmail 자바 클래스를 pastebin에 올려 놓았습니다. "startSessionWithTLS"메소드에 특별한주의를 기울이고 동일한 기능을 제공하도록 JavaMail을 조정할 수 있습니다. http://pastebin.com/VE8Mqkqp


아마도 당신은 당신의 대답에 조금 더 제공 할 수 있습니까?
Antti Haapala 2016 년

1

코드는 SMTP 서버와의 연결 설정과 별도로 작동합니다. 이메일을 보내려면 실행중인 메일 (SMTP) 서버가 필요합니다.

수정 된 코드는 다음과 같습니다. 필요하지 않은 부분을 주석 처리하고 Authenticator가 필요하도록 세션 생성을 변경했습니다. 이제 사용하려는 SMPT_HOSTNAME, USERNAME 및 PASSWORD를 찾으십시오 (일반적으로 인터넷 제공 업체에서 제공).

Windows에서는 로컬 메일 서버를 실행하는 것이 그다지 간단하지 않기 때문에 (내가 아는 원격 SMTP 서버를 사용하여) 항상 이렇게합니다 (리눅스에서는 매우 쉽습니다).

import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

//import javax.activation.*;

public class SendEmail {

    private static String SMPT_HOSTNAME = "";
    private static String USERNAME = "";
    private static String PASSWORD = "";

    public static void main(String[] args) {

        // Recipient's email ID needs to be mentioned.
        String to = "abcd@gmail.com";

        // Sender's email ID needs to be mentioned
        String from = "web@gmail.com";

        // Assuming you are sending email from localhost
        // String host = "localhost";

        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        properties.setProperty("mail.smtp.host", SMPT_HOSTNAME);

        // Get the default Session object.
        // Session session = Session.getDefaultInstance(properties);

        // create a session with an Authenticator
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                    to));

            // Set Subject: header field
            message.setSubject("This is the Subject Line!");

            // Now set the actual message
            message.setText("This is actual message");

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

1

실제로 465가 작동하고 예외는 SMTP 포트 25가 열려 있지 않기 때문일 수 있습니다. 기본적으로 포트 번호는 25입니다. 그러나 오픈 소스로 제공되는 메일 에이전트 인 Mercury를 사용하여 구성 할 수 있습니다.

단순성을 위해 다음 구성을 사용하면 괜찮습니다.

// Setup your mail server
props.put("mail.smtp.host", SMTP_HOST); 
props.put("mail.smtp.user",FROM_NAME);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.EnableSSL.enable","true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
props.setProperty("mail.smtp.socketFactory.fallback", "false");  
props.setProperty("mail.smtp.port", "465");  
props.setProperty("mail.smtp.socketFactory.port", "465");

더 많은 정보 : 여기 에서 처음부터 전체 작업 예제를 확인 하십시오.


1

나는 당신이 얻은 것과 같은 예외가 있습니다. 그 이유는 컴퓨터에서 smpt 서버를 설치하고 실행하지 않기 때문입니다 (호스트가 localhost이므로). Windows 7을 사용하는 경우 SMTP 서버가 없습니다. 그래서 당신은 도메인으로 다운로드, 설치 및 구성하고 계정을 만들어야합니다. 저는 hmailserver를 내 로컬 컴퓨터에 설치하고 구성하는 smtp 서버로 사용했습니다. https://www.hmailserver.com/download


-2

여기에서 Google (gmail) 계정을 사용하여 이메일을 보내기위한 완전하고 매우 간단한 Java 클래스를 찾을 수 있습니다.

자바 및 Google 계정을 사용하여 이메일 보내기

다음 속성을 사용합니다.

Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");

1
링크 전용 답변은 SO에서 권장되지 않습니다. 답변 자체에 답변을 포함하는 것이 좋습니다.
laalto 2013
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.