使用 smtp 从服务发送邮件

Sending mail from service using smtp

我的应用程序运行发送和电子邮件的服务,这对用户来说必须是透明的,所以我使用 javax.mail。

这些是我实现的类:

JSSEProvider.java

public final class JSSEProvider extends Provider {
    private static final long serialVersionUID = 1L;

    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
            @Override
            public Void run() {
                put("SSLContext.TLS",
                    "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                    "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
            put("TrustManagerFactory.X509",
                    "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
            return null;
            }
        });
    }
}

MailSender.java

public class MailSender extends javax.mail.Authenticator {
    private final String mailhost = "smtp.gmail.com";
    private final String user;
    private final String password;
    private final Session session;

    static {
        Security.addProvider(new JSSEProvider());
    }

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

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactor.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getDefaultInstance(props, this);
    }

    @Override
    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);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));

        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
        message.setDataHandler(handler);

        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 class ByteArrayDataSource implements DataSource {
        private final 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;
        }

        @Override
        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }

        @Override
        public String getName() {
            return "ByteArrayDataSource";
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }
}

最后,这是我从服务发送电子邮件的方式:

private void sendEmail(String email) {
    String from = "mymail@gmail.com";
    String pass = "mypass";
    String to = email;
    String subject = getString(R.string.email_subject);
    String body = text_i_want_to_send;

    MailSender mail = new MailSender(from, pass);

    try {
        mail.sendMail(subject, body, from, to);
        Log.d("EMAIL", "Email sent!");
    } catch (Exception e) {
        Log.d("EMAIL", "Error: " + e.getMessage());
    }
}

现在的问题是,当它应该发送电子邮件时,我可以在 LogCat 中看到引用 catch 语句的异常,但它没有提供任何细节,它只是说:

EMAIL    Error: null

不得不说,我已经从网络上关于使用 javax.mail 使用 smtp 发送邮件的不同教程中获得了 JSSEProvider 和 MailSender 类。

所以,我不知道我做错了什么

编辑 --

我查到异常了,和主线程做网络操作有关。所以我现在使用 AsyncTask 并且这部分已解决。

但是现在,我又遇到了一个异常,这次是与身份验证相关的。我在我的电子邮件帐户中收到一封电子邮件,告诉我有人试图访问我的帐户(我)并且 gmail 已阻止它。那么,我该如何解决这个身份验证问题呢?

你能为 NullPointerException 添加一个 catch 吗? (并添加抛出 e)。 我猜你在某处有一个空指针,这样你可以获得更多数据。 所以抓"Exception"是个坏习惯,什么都会抓。