简体   繁体   English

使用smtp从服务发送邮件

[英]Sending mail from service using smtp

My app runs a service which sends and email, this must be transparent for the user, so I use javax.mail. 我的应用程序运行一个发送和发送电子邮件的服务,该服务对于用户而言必须是透明的,因此我使用javax.mail。

These are the classes I implement: 这些是我实现的类:

JSSEProvider.java 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 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");
        }
    }
}

And finally, this is how I send the email from service: 最后,这是我从服务发送电子邮件的方式:

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());
    }
}

Now, the problem is that, when it should send the email, I can see in the LogCat the exception refered to the catch statement, but it does not give any details, it just says: 现在的问题是,当它应该发送电子邮件时,我可以在LogCat中看到引用到catch语句的异常,但是它没有提供任何详细信息,它只是说:

EMAIL    Error: null

Have to say that I have goten the JSSEProvider and the MailSender clases from the diferent tutorials around the net about using javax.mail to send mails using smtp. 不得不说,我从网络上有关使用javax.mail通过smtp发送邮件的各种教程中获得了JSSEProvider和MailSender的案例。

So, I have no clue about what I'm doing wrong 所以,我不知道自己在做什么错

EDIT -- 编辑-

I have chaught the exception, and it was related to doing network operation on the main thread. 我已经找到了例外,它与在主线程上进行网络操作有关。 So I'm using now an AsyncTask and this part is solved. 因此,我现在正在使用AsyncTask并解决了这一部分。

But now, I have another exception, related to authentication this time. 但是现在,我有另一个例外,这次与身份验证有关。 I have received an email in my email account telling that some has tried to access to my account (me) and that gmail has blocked it. 我已在我的电子邮件帐户中收到一封电子邮件,告知某些人试图访问我的帐户(me),而gmail已将其阻止。 So, how can I solve this authentication issue? 那么,如何解决此身份验证问题?

Can you add a catch for a NullPointerException? 您可以为NullPointerException添加捕获吗? (and add throw e). (并添加throw e)。 I guess you have a null pointer somewhere and like this you can have more data. 我猜你在某个地方有一个空指针,这样你可以拥有更多的数据。 Therefor it's a bad habit to catch "Exception" as everything will be caught. 因此,捕获“异常”是一个坏习惯,因为一切都会被捕获。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM