有关使GMailSender正常工作的问题。继续https://stackoverflow.com/questions/23533439/android-issue-with-getting-gmailsender-to-work

问题描述 投票:0回答:1

我已经尝试了所有替代方法,但是我的GMailSender仍然无法正常工作,请您帮忙找出问题所在?或者,也非常欢迎通过gmail发送电子邮件的另一种方法。

我将所有错误复制到尝试的每个端口下面。注意:该权限在AndroidManifest文件中提供。我也从AsyncTask调用了GMailSender。非常感谢,

public class GMailSender extends javax.mail.Authenticator {
    private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;
    private Multipart _multipart;
    static {
        Security.addProvider(new JSSEProvider());

    }
    public GMailSender(String user, String password) {
        this.user = user;
        this.password = password;

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587");
        //443 doesn't work (Connection refused)
        //465 doesn't work javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        //587,25 doesn't work, javax.net.ssl.SSLHandshakeException: SSL handshake aborted: ssl=0x83ca3680: I/O error during system call, Connection reset by peer
        props.put("mail.smtp.socketFactory.port", "587");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.starttls.enable", true);
        props.setProperty("mail.smtp.quitwait", "false");
        props.put("mail.smtp.debug", "true");
        props.put("javax.activation.debug", "true");


        session = Session.getDefaultInstance(props, this);
        session.setDebug(true);
    }
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }
    public synchronized void sendMail(String subject, String body,
                                      String sender, String recipients) throws Exception {
        MimeMessage message = new MimeMessage(session);
        System.out.println("Inside GMailSender, sendMail, session: " + session);
        System.out.println("Inside GMailSender, sendMail, session.getProperty(): " + session.getProperty("mail.smtp.port"));
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
        message.setDataHandler(handler);
        System.out.println("Inside GMailSender, sendMail, message: " + message);
        if (recipients.indexOf(',') > 0)
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        else
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        Transport.send(message);
    }

    public void addAttachment(String filename) throws Exception
    {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        _multipart.addBodyPart(messageBodyPart);
    }

    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;
        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }
        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }
        public void setType(String type) {
            this.type = type;
        }
        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }
        public String getName() {
            return "ByteArrayDataSource";
        }
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }

}

日志

session: javax.mail.Session@78308db1
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Can't send command to SMTP host;
  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
    at com.example.testinglib.MyTesting.main(MyTesting.java:48)
Caused by: javax.mail.MessagingException: Can't send command to SMTP host;
  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
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1564)
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1551)
    at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:935)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:426)
    at javax.mail.Service.connect(Service.java:310)
    at javax.mail.Service.connect(Service.java:169)
    at javax.mail.Service.connect(Service.java:118)
    at javax.mail.Transport.send0(Transport.java:188)
    at javax.mail.Transport.send(Transport.java:118)
    at com.example.testinglib.MyTesting.main(MyTesting.java:43)
Caused by: 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
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1959) 
java android gmail javamail
1个回答
0
投票

我找到了一个较短的解决方案:

package com.example.mail;

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 SendMailTLS {

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "password";

        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");

        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("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
            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);
        }
    }
}

来源:Sending Email via JavaMail API

希望这会有所帮助!祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.