如何在android eclipse中发送电子邮件?

时间:2015-02-20 12:31:21

标签: java android eclipse android-asynctask

private class RetriveTask extends AsyncTask<String,Void,Void>{
    @Override
     protected void onPreExecute() {
        prop = new Properties();
        prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.port", "465");



        session = Session.getDefaultInstance(prop,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username,password);
                    }
                }); 
    };
     @Override
     protected Void doInBackground(String... params) {
         try{
             Message message = new MimeMessage(session);
             message.setFrom(new InternetAddress("dev.montaser@gmail.com"));
             message.setRecipients(Message.RecipientType.TO,
                     InternetAddress.parse("eng.montaser99@yahoo.com"));
             message.setSubject("Test JCG Example");
             message.setContent("Hello how are you","text/html; charset=utf-8");

             Transport.send(message);

         } catch (AddressException e) {
             Toast.makeText(getBaseContext(),"Problem in addree",Toast.LENGTH_LONG).show();

         } catch (MessagingException e) {
             Toast.makeText(getBaseContext(),"Problem in message",Toast.LENGTH_LONG).show();

         }
         return null;
     }

     @Override
     protected void onPostExecute(Void s) {
         Toast.makeText(context,"Message send",Toast.LENGTH_LONG).show();
     }
 }

日志:

02-20 12:04:50.115: E/AndroidRuntime(2052): FATAL EXCEPTION: main
02-20 12:04:50.115: E/AndroidRuntime(2052): Process: com.example.control, PID: 2052
02-20 12:04:50.115: E/AndroidRuntime(2052): java.lang.NoClassDefFoundError: com.example.control.MainActivity$RetriveTask$1
02-20 12:04:50.115: E/AndroidRuntime(2052):     at com.example.control.MainActivity$RetriveTask.onPreExecute(MainActivity.java:149)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at android.os.AsyncTask.execute(AsyncTask.java:535)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at com.example.control.MainActivity$1.onClick(MainActivity.java:62)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at android.view.View.performClick(View.java:4756)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at android.view.View$PerformClick.run(View.java:19749)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at android.os.Handler.handleCallback(Handler.java:739)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at android.os.Handler.dispatchMessage(Handler.java:95)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at android.os.Looper.loop(Looper.java:135)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at android.app.ActivityThread.main(ActivityThread.java:5221)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at java.lang.reflect.Method.invoke(Native Method)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at java.lang.reflect.Method.invoke(Method.java:372)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-20 12:04:50.115: E/AndroidRuntime(2052):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

2 个答案:

答案 0 :(得分:0)

一个意图是最简单的方法,老实说,一点点谷歌搜索没有伤害!

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"example@example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject");
i.putExtra(Intent.EXTRA_TEXT   , "body / text here");

//send
try {
    startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}

答案 1 :(得分:0)

我建议您在类这样的课程中收集邮件发件人设置:

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

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

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

        Properties props = new Properties();   
        props.put("mail.smtp.user", user);
        props.put("mail.smtp.auth", "true");   
        props.put("mail.smtp.host", mailhost);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "587");  
        props.put("mail.debug", "true");

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

    protected PasswordAuthentication getPasswordAuthentication() {   
        return new PasswordAuthentication(user, password);   
    }   

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {   
        try{
            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 t = session.getTransport("smtp");
            t.connect(mailhost, user, password);
            t.sendMessage(message, message.getAllRecipients());

        }catch(Exception e){
            e.printStackTrace();
        }
    }   

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

使用此类并使用该函数在AsynchTask上发送邮件:

private void sendMail()
{
    GmailSender sender = new GmailSender("yourMailAddress", "yourPassword");
    try {
        sender.sendMail("YourTitle",   
                "mailContent",   
                "fromMailAdress",   
                "toMailAdress");
    } catch (Exception e) {
        e.printStackTrace();
    }   
}

onDoingBackground()方法上调用此方法,然后就可以了。

注意:还要确保已从Properties-&gt; Java Build Path

导入了javax库

修改:我忘记添加提供程序类:

public final class JSSEProvider extends Provider {

    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
            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;
            }
        });
    }
}