0

我正在使用以下代码在我的应用程序中发送电子邮件

在不使用默认/内置应用程序的情况下使用 JavaMail API 在 Android 中发送电子邮件

这以前有效,但现在因 NetworkOnMainThreadExceoption 而停止。我知道解决方案是使用 AsyncTask,但我不知道如何转换我现在拥有的类以使用 AsyncTask。以前没用过。

下面是失败的类的发送部分

public class EmailProvider extends Authenticator { 
    private static String emailUsername  = ""; 
    private static String emailPassword = "";
    private static String emailFrom  = ""; 
    private static String emailDefaultSMTPport = 
    private static String emailDefaultSocketFactoryPort = 
    private static String emailHost = ""; 

    private boolean emailAuth; 
    private boolean emailDebuggable; 

    private Multipart emailMultipart; 

    public EmailProvider(Context context) { 
        //this.context = context;

        emailDebuggable = false; // debug mode on or off - default off 
        emailAuth = true; // smtp authentication - default on 

        emailMultipart = new MimeMultipart(); 

    } 

    public boolean send(String emailAddress, String pEmailSubject, String pEmailBody) throws Exception { 

        Properties props = setProperties(); 

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

        MimeMessage msg = new MimeMessage(session); 

        msg.setFrom(new InternetAddress(emailFrom)); 

        msg.setRecipients(MimeMessage.RecipientType.TO, emailAddress); 

        msg.setSubject(pEmailSubject); 
        msg.setSentDate(new Date()); 

        // setup message body 
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(pEmailBody);

        emailMultipart.addBodyPart(messageBodyPart); 

        // Put parts in message 
        msg.setContent(emailMultipart); 

        // send email 
        Transport.send(msg); 

        return true; 
    } 

}

谢谢你的时间

4

1 回答 1

0

在你调用方法asyncTask的地方声明这个:activitysend()

private class SendEmailTask extends AsyncTask<Object, Object, Object> {        
        @Override
        protected Object doInBackground(Object... arg0) {
            yourEmailProviderObj.send(emailAddress, pEmailSubject, pEmailBody);
            return "executed";
        }
}

并进行此调用而不是您的send()方法调用:

new SendEmailTask().execute();

谢谢。

于 2013-01-21T22:43:15.527 回答