Flutter邮件发送功能插件flutter_email_sender的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter邮件发送功能插件flutter_email_sender的使用

flutter_email_sender 插件允许在Flutter中使用原生平台功能发送电子邮件。在Android上,它通过意图打开默认的邮件应用程序;而在iOS上,则是使用 MFMailComposeViewController 来撰写邮件。

使用示例

下面是一个完整的示例demo,展示了如何使用 flutter_email_sender 插件来构建一个简单的邮件发送界面,包括选择附件、编辑邮件内容以及实际发送邮件的功能。

示例代码

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_email_sender/flutter_email_sender.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.red),
      home: EmailSender(),
    );
  }
}

class EmailSender extends StatefulWidget {
  const EmailSender({Key? key}) : super(key: key);

  @override
  _EmailSenderState createState() => _EmailSenderState();
}

class _EmailSenderState extends State<EmailSender> {
  List<String> attachments = [];
  bool isHTML = false;

  final _recipientController = TextEditingController(
    text: 'example@example.com',
  );

  final _subjectController = TextEditingController(text: 'The subject');

  final _bodyController = TextEditingController(
    text: 'Mail body.',
  );

  Future<void> send() async {
    final Email email = Email(
      body: _bodyController.text,
      subject: _subjectController.text,
      recipients: [_recipientController.text],
      attachmentPaths: attachments,
      isHTML: isHTML,
    );

    String platformResponse;

    try {
      await FlutterEmailSender.send(email);
      platformResponse = 'success';
    } catch (error) {
      print(error);
      platformResponse = error.toString();
    }

    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(platformResponse),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Plugin example app'),
        actions: <Widget>[
          IconButton(
            onPressed: send,
            icon: Icon(Icons.send),
          )
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(8.0),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.all(8.0),
              child: TextField(
                controller: _recipientController,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Recipient',
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(8.0),
              child: TextField(
                controller: _subjectController,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Subject',
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.all(8.0),
                child: TextField(
                  controller: _bodyController,
                  maxLines: null,
                  expands: true,
                  textAlignVertical: TextAlignVertical.top,
                  decoration: InputDecoration(
                      labelText: 'Body', border: OutlineInputBorder()),
                ),
              ),
            ),
            CheckboxListTile(
              contentPadding:
                  EdgeInsets.symmetric(vertical: 0.0, horizontal: 8.0),
              title: Text('HTML'),
              onChanged: (bool? value) {
                if (value != null) {
                  setState(() {
                    isHTML = value;
                  });
                }
              },
              value: isHTML,
            ),
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Column(
                children: <Widget>[
                  for (var i = 0; i < attachments.length; i++)
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: Text(
                            attachments[i],
                            softWrap: false,
                            overflow: TextOverflow.fade,
                          ),
                        ),
                        IconButton(
                          icon: Icon(Icons.remove_circle),
                          onPressed: () => {_removeAttachment(i)},
                        )
                      ],
                    ),
                  Align(
                    alignment: Alignment.centerRight,
                    child: IconButton(
                      icon: Icon(Icons.attach_file),
                      onPressed: _openImagePicker,
                    ),
                  ),
                  TextButton(
                    child: Text('Attach file in app documents directory'),
                    onPressed: () => _attachFileFromAppDocumentsDirectoy(),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _openImagePicker() async {
    final picker = ImagePicker();
    final pick = await picker.pickImage(source: ImageSource.gallery);
    if (pick != null) {
      setState(() {
        attachments.add(pick.path);
      });
    }
  }

  void _removeAttachment(int index) {
    setState(() {
      attachments.removeAt(index);
    });
  }

  Future<void> _attachFileFromAppDocumentsDirectoy() async {
    try {
      final appDocumentDir = await getApplicationDocumentsDirectory();
      final filePath = appDocumentDir.path + '/file.txt';
      final file = File(filePath);
      await file.writeAsString('Text file in app directory');

      setState(() {
        attachments.add(filePath);
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Failed to create file in application directory'),
        ),
      );
    }
  }
}

Android配置

对于Android 11及以上版本,由于引入了包可见性(Package Visibility),需要在 AndroidManifest.xml 中添加以下内容以确保应用能够查询到其他已安装的应用程序:

<manifest package="com.mycompany.myapp">
  <queries>
    <intent>
      <action android:name="android.intent.action.SENDTO" />
      <data android:scheme="mailto" />
    </intent>
  </queries>
</manifest>

开始使用

如果您刚开始接触Flutter,可以通过访问 Flutter官方文档 获取更多信息。如果您想要编辑插件代码,请参阅 开发包文档

以上就是关于 flutter_email_sender 插件的基本介绍和使用方法,希望对您有所帮助!


更多关于Flutter邮件发送功能插件flutter_email_sender的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter邮件发送功能插件flutter_email_sender的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中使用flutter_email_sender插件来发送邮件的示例代码。这个插件允许你通过设备的默认邮件客户端发送电子邮件。

首先,确保你已经在pubspec.yaml文件中添加了flutter_email_sender依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_email_sender: ^5.0.2  # 确保版本号是最新的

然后运行flutter pub get来安装依赖。

接下来,你可以在你的Flutter项目中使用该插件。以下是一个简单的示例,展示了如何配置和发送邮件:

import 'package:flutter/material.dart';
import 'package:flutter_email_sender/flutter_email_sender.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Email Sender Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: EmailSenderScreen(),
    );
  }
}

class EmailSenderScreen extends StatefulWidget {
  @override
  _EmailSenderScreenState createState() => _EmailSenderScreenState();
}

class _EmailSenderScreenState extends State<EmailSenderScreen> {
  final EmailSender _emailSender = EmailSender();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Send Email'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _sendEmail,
          child: Text('Send Email'),
        ),
      ),
    );
  }

  Future<void> _sendEmail() async {
    final Email email = Email(
      body: "This is the email body.",
      subject: "This is the subject",
      recipients: ['example@example.com'],
      isHTML: false,
      attachmentPaths: [], // 如果需要附件,可以添加文件路径列表
    );

    try {
      await _emailSender.send(email);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Email sent successfully!')),
      );
    } catch (error) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to send email: $error')),
      );
    }
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个按钮,点击该按钮会尝试发送一封电子邮件。Email对象包含了邮件的正文、主题、收件人列表、是否HTML格式以及附件路径列表(本例中为空)。

注意事项:

  1. 权限:在Android上,你可能需要在AndroidManifest.xml中添加适当的权限来访问互联网(如果你的邮件客户端需要网络访问)。然而,flutter_email_sender通常使用设备上的默认邮件客户端,因此通常不需要额外的权限。

  2. 依赖设备:此插件依赖于设备上安装的邮件客户端。如果设备上没有安装任何邮件客户端,或者默认邮件客户端不支持通过Intent发送邮件,则可能无法发送邮件。

  3. 附件:如果发送附件,请确保提供的文件路径是设备上存在的有效路径。

  4. 错误处理:示例代码中包含了基本的错误处理,以显示发送邮件是否成功。

这个示例应该能帮助你理解如何在Flutter应用中使用flutter_email_sender插件来发送邮件。

回到顶部