使用smtp从服务发送邮件

时间:2015-04-16 09:41:46

标签: java android email 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

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

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

编辑 -

我已经处理了异常,它与在主线程上进行网络操作有关。所以我现在使用的是AsyncTask,这个部分已经解决了。

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

1 个答案:

答案 0 :(得分:1)

你能为NullPointerException添加一个catch吗? (并添加掷e)。 我猜你在某个地方有一个空指针,你可以拥有更多的数据。 因此,捕捉&#34;异常&#34;是一个坏习惯。因为一切都会被抓住。