简体   繁体   中英

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.

These are the classes I implement:

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

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:

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.

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.

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. So, how can I solve this authentication issue?

Can you add a catch for a NullPointerException? (and add 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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