Sending Email
Sending Email
public class MainActivity extends AppCompatActivity {
private EditText eTo;
private EditText eSubject;
private EditText eMsg;
private Button btn;
• @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eTo = (EditText)findViewById(R.id.txtTo);
eSubject = (EditText)findViewById(R.id.txtSub);
eMsg = (EditText)findViewById(R.id.txtMsg);
btn = (Button)findViewById(R.id.btnSend);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, new String[]
{eTo.getText().toString()});
it.putExtra(Intent.EXTRA_SUBJECT,eSubject.getText().toString());
it.putExtra(Intent.EXTRA_TEXT,eMsg.getText());
it.setType("message/rfc822");
startActivity(Intent.createChooser(it,"Choose Mail App"));
}
});
}
}
We need to add MIME type in our android manifest file for that open android
manifest file (AndroidManifest.xml) and write the code like as shown below
• <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/
android" package="com.tutlane.sendmailexample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="message/rfc822"/>
</intent-filter>
</activity>
</application>
</manifest>
• If you observe above AndroidManifest.xml file we added following
extra fields of Intent filters.
• action - we use this property to define that the activity can perform
SEND action.
• category - we included the DEFAULT category for this activity to be
able to receive implicit intents.
• data - the type of data the activity can send.