Flutter邮件发送插件smtpexpress的使用

Flutter邮件发送插件smtpexpress的使用

SMTP Express Package

这是一个用于通过SMTP Express发送电子邮件的插件。

获取开始

pubspec.yaml文件中添加SMTP Express包依赖:

dependencies:
  smtpexpress: 0.0.2

导入

导入Flutter的SMTP Express包:

import 'package:smtpexpress/smtpexpress.dart';

使用

以下是一个完整的示例,展示如何在Flutter应用中使用SMTP Express发送电子邮件。

import 'package:flutter/material.dart';
import 'package:smtpexpress/smtpexpress.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // 这个小部件是你的应用的根。
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SmtpExpress Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  [@override](/user/override)
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  List<String?> filePaths = [];

  var smtpExpressClient = createClient(
    CredentialOptions(
      projectSecret: '28627898db4affbb5e882aaee3617cbd293fddc15a9059a51e',
      projectId: 'sm0pid-s9RFHSey4FMnk5OjCUeuSBjq2'
    )
  );

  startSmtpExpress() async {
    try {
      // 准备SendMailOptions
      final options = SendMailOptions(
        subject: '测试邮件',
        sender: MailSender(name: 'Ibukun', email: 'sm0pid-s9RFHSey4FMnk5OjCUeuSBjq2@projects.smtpexpress.com'),
        recipients: ['ibkokunoye@gmail.com'],
        // 可选地包含附件、模板或日历事件
        message: '这是一封使用SMTP Express发送的测试邮件',
        attachments: filePaths,
        calendarEvent: CalendarEventOptions(
          title: '与Ibk的会议',
          startDate: DateTime.now(),
          endDate: DateTime.now().add(const Duration(days: 3)),
        ),
      );

      // 发送邮件
      final response = await smtpExpressClient.sendApi.sendMail(options);

      // 处理成功的响应
      if (kDebugMode) {
        print('响应: $response');
      }
    } catch (error) {
      // 处理错误
      if (kDebugMode) {
        print('发送邮件时出错: $error');
      }
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            OutlinedButton(
              onPressed: () {
                // 开始SMTP Express
                startSmtpExpress();
              },
              child: const Text('发送邮件'),
            ),

            const SizedBox(height: 8),

            // 选择文件
            ElevatedButton(
              onPressed: () async {
                // 触发文件选择
                final result = await FilePicker.platform.pickFiles(allowMultiple: true);

                if (result != null) {
                  // 对文件路径进行操作,例如显示或打开文件
                  filePaths = result.paths;
                } else {
                  // 用户取消了选择
                }
              },
              child: const Text('选择文件'),
            ),
          ],
        ),
      )
    );
  }
}

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

1 回复

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


SmtpExpress 是一个用于在 Flutter 应用中发送邮件的插件。它允许你通过 SMTP 服务器发送电子邮件。以下是如何在 Flutter 项目中使用 smtpexpress 的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 smtpexpress 的依赖:

dependencies:
  flutter:
    sdk: flutter
  smtpexpress: ^1.0.0  # 请确保使用最新版本

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

2. 配置 SMTP 服务器信息

你需要提供 SMTP 服务器的详细信息,如主机地址、端口、用户名和密码。这些信息通常由你的电子邮件服务提供商提供。

3. 编写代码发送邮件

以下是一个使用 smtpexpress 发送邮件的示例代码:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('SmtpExpress Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // 配置 SMTP 服务器
              final smtpConfig = SmtpConfig(
                host: 'smtp.example.com',  // SMTP 服务器地址
                port: 587,  // 端口号(通常是 587 或 465)
                username: 'your_email@example.com',  // 你的邮箱地址
                password: 'your_password',  // 你的邮箱密码
                enableTls: true,  // 是否启用 TLS(通常为 true)
              );

              // 创建邮件
              final email = SmtpEmail(
                from: 'your_email@example.com',
                recipients: ['recipient@example.com'],
                subject: 'Test Email',
                content: 'This is a test email from SmtpExpress.',
              );

              // 发送邮件
              try {
                await SmtpExpress.sendEmail(smtpConfig, email);
                print('Email sent successfully');
              } catch (e) {
                print('Failed to send email: $e');
              }
            },
            child: Text('Send Email'),
          ),
        ),
      ),
    );
  }
}
回到顶部