Avatar billede it-dyret Nybegynder
03. oktober 2011 - 16:41 Der er 3 kommentarer og
1 løsning

Sende mail via Gmail

Hej, jeg forsøger at sende en mail via Gmail, men jeg får følgende fejl:

javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Jeg kan ikke gennemskue, hvad jeg gør forkert.


Min kode ser således ud:

import java.util.Properties;
import javax.mail.Authenticator;
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 GmailSender {

    private static String HOST = "smtp.gmail.com";
    private static String USER = "my_account@gmail.com";
    private static String PASSWORD = "my_password";
    private static String PORT = "587";
    private static String FROM = "my_account@gmail.com";
    private static String TO = "recipient@mydomain.com";

    private static String STARTTLS = "true";
    private static String AUTH = "true";
    private static String DEBUG = "true";
    private static String SUBJECT = "Testing mail through gmail";
    private static String TEXT = "Mail body";

    public static synchronized void send() {
        //Use Properties object to set environment properties
        Properties props = System.getProperties();

        props.put("mail.smtp.starttls.enable", STARTTLS);
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.user", USER);
        props.put("mail.smtp.password", PASSWORD);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.auth", AUTH);
        props.put("mail.smtp.debug", DEBUG);

        try {
            Authenticator auth = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USER, PASSWORD);
                }
            };
         
            Session session = Session.getDefaultInstance(props, auth);

            MimeMessage message = new MimeMessage(session);
            message.setText(TEXT);
            message.setSubject(SUBJECT);
            message.setFrom(new InternetAddress(FROM));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));

            Transport transport = session.getTransport("smtp");
            transport.connect();
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
      GmailSender.send();
      System.out.println("Mail sent successfully!");
    }
}
Avatar billede arne_v Ekspert
03. oktober 2011 - 16:49 #1
Du kunne proeve med:

        SSLContext sslctx = SSLContext.getInstance("SSL");
        sslctx.init(null, new X509TrustManager[] { new MyTrustManager() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sslctx.getSocketFactory());

hvor:

class MyTrustManager implements X509TrustManager
{
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
    }
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
    }
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}
Avatar billede arne_v Ekspert
03. oktober 2011 - 16:49 #2
Du faar saa ikke checket certfifikat .................
Avatar billede it-dyret Nybegynder
04. oktober 2011 - 11:23 #3
Hej, tak for respons. Desværre får jeg fortsat samme fejl. Min kode ser nu således ud (jeg er lidt usikker på, hvor jeg skal forsøge at tilføje den kode, du har foreslået).

import java.security.cert.X509Certificate;
import java.util.Properties;
import javax.mail.Authenticator;
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;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;

public class GmailSender {

    private static String HOST = "smtp.gmail.com";
    private static String USER = "my_account@gmail.com";
    private static String PASSWORD = "my_password";
    private static String PORT = "587";
    private static String FROM = "my_account@gmail.com";
    private static String TO = "recipient@mydomain.com";

    private static String STARTTLS = "true";
    private static String AUTH = "true";
    private static String DEBUG = "true";
    private static String SUBJECT = "Testing mail through gmail";
    private static String TEXT = "Mail body";

    public static synchronized void send() {
        //Use Properties object to set environment properties
        Properties props = System.getProperties();

        props.put("mail.smtp.starttls.enable", STARTTLS);
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.user", USER);
        props.put("mail.smtp.password", PASSWORD);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.auth", AUTH);
        props.put("mail.smtp.debug", DEBUG);

        try {
            Authenticator auth = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USER, PASSWORD);
                }
            };
         
            Session session = Session.getDefaultInstance(props, auth);

            MimeMessage message = new MimeMessage(session);
            message.setText(TEXT);
            message.setSubject(SUBJECT);
            message.setFrom(new InternetAddress(FROM));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));

      X509TrustManager x509 = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }
       
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }
       
        @Override
        public X509Certificate[] getAcceptedIssuers() {
          return new X509Certificate[0];
        }
      };

      SSLContext sslctx = SSLContext.getInstance("SSL");
      sslctx.init(null, new X509TrustManager[] { x509 }, null);
      HttpsURLConnection.setDefaultSSLSocketFactory(sslctx.getSocketFactory());

      Transport transport = session.getTransport("smtp");
      transport.connect();
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    GmailSender.send();
    System.out.println("Mail sent successfully!");
  }
}
Avatar billede it-dyret Nybegynder
04. oktober 2011 - 11:47 #4
Så spiller det endelig! Jeg fandt løsningen på https://forums.oracle.com/forums/thread.jspa?threadID=2042465.

Tricket er ganske enkelt at sætte følgende property:
props.put("mail.smtp.ssl.trust", HOST);

Den komplette kode ser således ud:

import java.util.Properties;
import javax.mail.Authenticator;
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 GmailSender {
    private static String HOST = "smtp.gmail.com";
    private static String USER = "my_account@gmail.com";
    private static String PASSWORD = "my_password";
    private static String PORT = "587";
    private static String FROM = "my_account@gmail.com";
    private static String TO = "recipient@mydomain.com";

    private static String STARTTLS = "true";
    private static String AUTH = "true";
    private static String DEBUG = "true";
    private static String SUBJECT = "Testing mail through gmail";
    private static String TEXT = "Mail body";

    public static synchronized void send() {
        //Use Properties object to set environment properties
        Properties props = System.getProperties();

        props.put("mail.smtp.starttls.enable", STARTTLS);
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.user", USER);
        props.put("mail.smtp.password", PASSWORD);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.auth", AUTH);
        props.put("mail.smtp.debug", DEBUG);
        props.put("mail.smtp.ssl.trust", HOST);

        try {
            Authenticator auth = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USER, PASSWORD);
                }
            };
         
            Session session = Session.getDefaultInstance(props, auth);

            MimeMessage message = new MimeMessage(session);
            message.setText(TEXT);
            message.setSubject(SUBJECT);
            message.setFrom(new InternetAddress(FROM));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));

            Transport transport = session.getTransport("smtp");
            transport.connect();
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
      GmailSender.send();
      System.out.println("Mail sent successfully!");
    }
}
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester