Android Studio实现邮箱发送Demo教程

recipe55777 7 0 rar 2023-03-10 14:03:15

以下是Android Studio实现可调用app的邮箱发送邮件的简单教程:

1. 添加依赖库

在项目的build.gradle文件中添加如下代码:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.0'
    implementation 'com.sun.mail:android-activation:1.6.0'
}

2. 编写邮件发送代码

在Activity中添加如下代码:

public void sendEmail() {
    String[] TO = {"recipient@example.com"};
    String[] CC = {"cc@example.com"};
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.setType("text/plain");

    emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
    emailIntent.putExtra(Intent.EXTRA_CC, CC);
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "邮件主题");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "邮件内容");

    try {
        startActivity(Intent.createChooser(emailIntent, "发送邮件"));
        finish();
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "没有找到邮件客户端", Toast.LENGTH_SHORT).show();
    }
}

3. 添加按钮调用发送代码

在布局文件中添加一个按钮,并在Activity中添加以下代码:

Button button = (Button) findViewById(R.id.send_email_button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        sendEmail();
    }
});

这样,当用户点击按钮时,便可调用app的邮箱发送邮件了。

用户评论
请输入评论内容
评分:
暂无评论