【问题标题】:Issue with sending email发送电子邮件的问题
【发布时间】:2015-10-16 11:20:11
【问题描述】:

我尝试在唤醒的广播接收器中使用此后台电子邮件发件人代码 (https://github.com/kristijandraca/BackgroundMailLibrary) 发送电子邮件,但在进行一些调整时,我了解到由于某种原因,当手机被锁定并打开时,它无法再发送电子邮件无线上网。这是相关代码和错误报告。我将不胜感激任何建议。 在错误报告中,我将所有与日期无关的部分都加粗,以便于阅读

主要:

private PendingIntent pendingIntent;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flight2);
public void start() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int interval = 8000;
        Intent alarmIntent = new Intent(Flight2.this,AlarmReceiver.class);
        PendingIntent pendingIntent= PendingIntent.getBroadcast(Flight2.this,0,alarmIntent,0);
        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }

    public void cancel() {
        Intent alarmIntent = new Intent(Flight2.this,AlarmReceiver.class);
        PendingIntent pendingIntent=     PendingIntent.getBroadcast(Flight2.this,0,alarmIntent,0);
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pendingIntent);
        Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();


    }

    public void startAt10(Calendar calendar) {







        Intent alarmIntent = new Intent(Flight2.this,AlarmReceiver.class);
        PendingIntent pendingIntent= PendingIntent.getBroadcast(Flight2.this,0,alarmIntent,0);







        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingintent;
        int interval = 1000 * 60 * 5;
        String Alarmset ="Alarmset";
        Toast.makeText(Flight2.this, Alarmset, Toast.LENGTH_SHORT).show();


        calendar.setTimeInMillis(System.currentTimeMillis());


        manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                interval, pendingIntent);
    }}

**Receiver:** 


public class AlarmReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, AlarmService.class);

        startWakefulService(context, service);
        Log.i("SimpleWakefulReceiver", "Running servicech1 "
                 );










    }



































}

服务:

public class AlarmService extends IntentService {

    public AlarmService() {
        super("SimpleWakefulService");
        Log.i("SimpleWakefulReceiver", "Running servicechshould run "
        );
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i("SimpleWakefulReceiver", "Running servicech2 "
        );













            BackgroundMail bm = new BackgroundMail(AlarmService.this);
            bm.setGmailUserName();
            bm.setGmailPassword();
            bm.setMailTo(email);
            bm.setFormSubject("My Blackbox Notification Update");
            bm.setFormBody(Body);
            bm.send();
            Log.i("SimpleWakefulReceiver", "Running servicech3 "
            );












        AlarmReceiver.completeWakefulIntent(intent);
    }

发件人:

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

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

public GmailSender(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.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.quitwait", "false");

    session = Session.getDefaultInstance(props, this);
    _multipart = new MimeMultipart();
}

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.setText(body);
    message.setDataHandler(handler);
    if(_multipart.getCount() > 0)
        message.setContent(_multipart);
    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 void addAttachment(String filename) throws Exception
{
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);

    _multipart.addBodyPart(messageBodyPart);
}

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

}

清单权限和接收者声明:

 <uses-permission android:name="android.permission.SEND_SMS" />

        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

        <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

错误报告:

07-27 20:31:19.690  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ javax.mail.AuthenticationFailedException
07-27 20:31:19.690  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at javax.mail.Service.connect(Service.java:319)
07-27 20:31:19.690  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at javax.mail.Service.connect(Service.java:169)
07-27 20:31:19.690  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at javax.mail.Service.connect(Service.java:118)
07-27 20:31:19.690  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at javax.mail.Transport.send0(Transport.java:188)
07-27 20:31:19.700  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at javax.mail.Transport.send(Transport.java:118)
07-27 20:31:19.700  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at holland.thomas.myblackbox2.GmailSender.sendMail(GmailSender.java:76)
07-27 20:31:19.700  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at holland.thomas.myblackbox2.BackgroundMail$startSendingEmail.doInBackground(BackgroundMail.java:117)
07-27 20:31:19.700  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at holland.thomas.myblackbox2.BackgroundMail$startSendingEmail.doInBackground(BackgroundMail.java:90)
07-27 20:31:19.700  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-27 20:31:19.700  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-27 20:31:19.710  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-27 20:31:19.710  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-27 20:31:19.710  22803-22952/holland.thomas.myblackbox2 W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

【问题讨论】:

  • 我删除了错误代码的中间部分,因为 stackoverflow 认为它是垃圾邮件,不让我全部发布。

标签: android email smtp connection broadcastreceiver


【解决方案1】:

试试这个对我有用:

 package com.javamail;

 import java.util.Properties;
 import javax.activation.DataHandler;
 import javax.activation.DataSource;
 import javax.activation.FileDataSource;
 import javax.mail.BodyPart;
 import javax.mail.Message;
 import javax.mail.Multipart;
 import javax.mail.PasswordAuthentication;
 import javax.mail.Session;
 import javax.mail.Transport;
 import javax.mail.internet.InternetAddress;
 import javax.mail.internet.MimeBodyPart;
 import javax.mail.internet.MimeMessage;
 import javax.mail.internet.MimeMultipart;
 import android.os.AsyncTask;
 import android.util.Log;


 public class Mail 
 { 
     MimeMessage message;
     private Multipart _multipart; 
     private String to_mail;
     private String subject;
     private String mailDescription;

public void addAttachment(String filename) throws Exception
{ 
    BodyPart messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(filename); 
    messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 

    _multipart.addBodyPart(messageBodyPart); 
} 

public Mail()
{ 

    _multipart = new MimeMultipart(); 
} 

public boolean send() throws Exception
{
    Properties props = new Properties();
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.host", "smtp.gmail.com");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    props.put("mail.debug", "true");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("orginalsenderemailaddress@gmail.com",
                    "password");
        }
    });

    session.setDebug(true);


    final Transport transport = session.getTransport();
    InternetAddress addressFrom = new InternetAddress(getToMail());
    message = new MimeMessage(session);
    message.setSender(addressFrom);
    message.setSubject(getSubject());
    message.setContent(getMailDescription(), "text/plain");
    message.addRecipient(Message.RecipientType.TO, addressFrom);
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            try {
                if (_multipart!=null) {
                     message.setContent(_multipart);
                }
                transport.connect();
                Transport.send(message);
                transport.close();
                Log.e("@@@@@@@@@@@@@@", "mail sent @@@@@@@@@@@@@@@@");

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }
    }.execute();

    return false;
}

public String getSubject() {
    return subject;
}

public void setSubject(String subject) {
    this.subject = subject;
}

public String getMailDescription() {
    return mailDescription;
}

public void setMailDescription(String mailDescription) {
    this.mailDescription = mailDescription;
}

public String getToMail() {
    return to_mail;
}

public void setToMail(String to_mail) {
    this.to_mail = to_mail;
} 


} 

如果网络可用,请在您想要的任何地方拨打此电话:

 if(new NetworkConnection(this).isConnectionAvailable())
 {
            sendEmail();
 }

这里是发件人:

 private void sendEmail() {
    Mail mail = new Mail();
        mail.setToMail("to mail address");
        mail.setSubject("Subject");
        mail.setMailDescription("Description");
        mail.addAttachment("file path")// if attachment is there
        try {
            mail.send();
        } catch (Exception e) {

            e.printStackTrace();
            Log.v(Email_Tag, ""+e);
        }


}

【讨论】:

  • 到目前为止一切都兼容,除了 import com.utils.AppConstants;和网络连接。你是从另一个图书馆得到的吗?对于网络连接,错误是它无法解决它。
  • 不,它是我项目的一部分。我刚刚编辑了我的代码 com.utils.AppConstants 是我的导入删除它。和 NetworkConnection 类是检查互联网是否可用,如果互联网可用,然后调用 sendEmail() 否则按照您的需要执行。如果满意就投票吧。
  • 我试过了,你的代码也出现了同样的错误。只有当手机在wifi上并且屏幕被锁定时它才不起作用。
猜你喜欢
  • 2012-01-02
  • 1970-01-01
  • 2016-08-12
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多