欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

发邮件

程序员文章站 2022-03-18 21:44:40
...
发送邮件使用android.content.Intent.ACTION_SEND,参数来实现通过手机发Email服务。收发Email的过程是通过android内置的Gmail程序,而非直接使用smtp的protocol,而模拟器上并未内置Gmail Client,因此该程序只能在真机上运行。
其实android中发送email有很多写法:
1.
Uri uri = Uri.parse("mailto:****@gmail.com");
Intent emailIntent = new Intent(Intent.ACTION_SEND,uri);
startActivity(emailIntent);

2. 如下面代码所示:
package com.kevin.email;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Main extends Activity {
private Button btn_send;
private EditText et_receiver,et_cc,et_subject,et_body;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et_receiver = (EditText) findViewById(R.id.et_receiver);
et_cc = (EditText) findViewById(R.id.et_attached);
et_subject = (EditText) findViewById(R.id.et_subject);
et_body = (EditText) findViewById(R.id.et_body);
btn_send = (Button) findViewById(R.id.btn_send);
btn_send.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// 通过Intent发送邮件
Intent emailIntent = new Intent("android.content.Intent.ACTION_SEND");
// 设置邮件格式
emailIntent.setType("plain/text");
// 取得收件人地址,抄送,主题,正文
String[] receiver = new String[]{et_receiver.getText().toString()};
String[] cc = new String[]{
et_cc.getText().toString()
};
// 邮件信息
String subject = et_subject.getText().toString();
String body = et_body.getText().toString();
emailIntent.putExtra("android.content.Intent.EXTRA_EMAIL", receiver);
emailIntent.putExtra("android.content.Intent.EXTRA_CC", cc);
emailIntent.putExtra("android.content.Intent.EXTRA_SUBJECT", subject);
emailIntent.putExtra("android.content.Intent.EXTRA_TEXT", body);
// 打开gmail并将相关参数传入
startActivity(Intent.createChooser(emailIntent, getString(R.string.send)));
}
});
}
}

上例中只是发送文字,如果你想发送有文件的email,代码如下:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,"file:///sdcard/music.mp3");
intent.setType("audio/mp3");
startActivity(Intent.createChooser(intent,"发送中..."));