如何发送带附件的电子邮件

时间:2013-12-27 15:24:27

标签: android android-intent email-attachments

我想在图库中添加图片附件到电子邮件,然后发送文字。这是我的代码(Email with attachment):

public class SendEmail extends Activity {

Button btnsend;
EditText txtreceiver;
EditText txtsubject;
EditText txtinfo;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.send_email);

    btnsend = (Button) findViewById(R.id.btnsend);
    txtreceiver = (EditText) findViewById(R.id.txtreceiver);
    txtsubject = (EditText) findViewById(R.id.txtsubject);
    txtinfo = (EditText) findViewById(R.id.txtinfo);

          btnsend.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View v) {

          String to = txtreceiver.getText().toString();
          String subject = txtsubject.getText().toString();
          String message = txtinfo.getText().toString();

          Intent email = new Intent(Intent.ACTION_SEND);
          email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
          //email.putExtra(Intent.EXTRA_CC, new String[]{ to});
          //email.putExtra(Intent.EXTRA_BCC, new String[]{to});
          email.putExtra(Intent.EXTRA_SUBJECT, subject);
          email.putExtra(Intent.EXTRA_TEXT, message);

          File root = Environment.getExternalStorageDirectory();
          String pathToMyAttachedFile="temp/attachement.xml";
          File file = new File(root, pathToMyAttachedFile);
          if (!file.exists() || !file.canRead()) {
              return;
          }
          Uri uri = Uri.fromFile(file);
          email.putExtra(Intent.EXTRA_STREAM, uri);

          //need this to prompts email client only
          email.setType("message/rfc822");

          startActivity(Intent.createChooser(email, "Choose an Email client:"));
    }
        });
    }
}

如果我删除此部分:

File root = Environment.getExternalStorageDirectory();
      String pathToMyAttachedFile="temp/attachement.xml";
      File file = new File(root, pathToMyAttachedFile);
      if (!file.exists() || !file.canRead()) {
          return;
      }
      Uri uri = Uri.fromFile(file);
      email.putExtra(Intent.EXTRA_STREAM, uri);

我可以发送电子邮件,但之后只有没有附件的文字。我的实施错了吗?我怎么能纠正它。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)