Flutter邮件处理插件mailslurp的使用
Flutter邮件处理插件mailslurp的使用
MailSlurp 是一个免费的 API,用于创建电子邮件账户。你可以在 Dart 和 Flutter 的代码和测试中发送和接收电子邮件。
快速链接
- Pub.dev 包页面
- GitHub 源码
- 获取 API 密钥
- 文档
安装
在 pubspec.yaml
文件中添加以下依赖:
dart pub add mailslurp
配置
首先,你需要用你的 MailSlurp API 密钥配置默认的 API 客户端:
import 'package:mailslurp/api.dart';
defaultApiClient.getAuthentication<ApiKeyAuth>('API_KEY').apiKey = 'YOUR_MAILSLURP_API_KEY';
使用控制器
MailSlurp Dart 库导出了映射到 REST API 的控制器。控制器方法返回 Future,可以在异步方法中使用这些 Future。
var inboxController = InboxControllerApi();
// future result
Future<Inbox> inbox = inboxController.createInboxWithOptions(CreateInboxDto());
// 或者异步使用
void main() async {
var inbox = await inboxController.createInboxWithOptions(CreateInboxDto());
}
创建电子邮件地址
你可以使用 InboxController
创建真实的电子邮件账户:
test('can create email addresses', () async {
var inboxController = InboxControllerApi();
var inbox = await inboxController.createInboxWithOptions(CreateInboxDto());
expect(inbox.emailAddress.contains("@mailslurp"), true);
});
发送电子邮件
使用 InboxController
和 inboxId
发送电子邮件:
test('can send emails', () async {
var inboxController = InboxControllerApi();
var inbox = await inboxController.createInboxWithOptions(CreateInboxDto());
var confirmation = await inboxController.sendEmailAndConfirm(inbox.id,
sendEmailOptions: SendEmailOptions(
to: [inbox.emailAddress],
subject: "Test email",
body: "<html>My message</html>",
isHTML: true
)
);
expect(confirmation.inboxId, inbox.id);
});
接收电子邮件
使用 WaitForController
和 inboxId
以及超时时间接收电子邮件:
test('can receive emails', () async {
var email = await waitForController.waitForLatestEmail(inboxId: inbox.id, timeout: 30000, unreadOnly: true);
expect(email.subject, "Test email");
});
测试用法
以下是一个完整的测试示例,展示如何创建电子邮件地址、发送和接收电子邮件:
import 'dart:io';
import 'package:test/test.dart';
import 'package:mailslurp/api.dart';
void main() async {
setUp(() {
// 从环境变量中读取 API 密钥
var apiKey = Platform.environment["API_KEY"];
expect(apiKey != null, true);
// 设置 API 密钥并实例化控制器
defaultApiClient.getAuthentication<ApiKeyAuth>('API_KEY').apiKey = apiKey;
});
test('can create email addresses', () async {
var inboxController = InboxControllerApi();
var inbox = await inboxController.createInboxWithOptions(CreateInboxDto());
expect(inbox.emailAddress.contains("@mailslurp"), true);
});
test('can send and receive emails', () async {
var inboxController = InboxControllerApi();
var waitForController = WaitForControllerApi();
var inbox = await inboxController.createInboxWithOptions(CreateInboxDto());
var confirmation = await inboxController.sendEmailAndConfirm(inbox.id,
sendEmailOptions: SendEmailOptions(
to: [inbox.emailAddress],
subject: "Test email",
body: "<html>My message</html>",
isHTML: true
)
);
expect(confirmation.inboxId, inbox.id);
var email = await waitForController.waitForLatestEmail(inboxId: inbox.id, timeout: 30000, unreadOnly: true);
expect(email.subject, "Test email");
});
}
更多关于Flutter邮件处理插件mailslurp的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter邮件处理插件mailslurp的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用mailslurp
插件来处理邮件的示例代码。需要注意的是,mailslurp
实际上是一个用于测试邮件的API服务,而Flutter本身并没有直接的mailslurp
插件,但你可以通过HTTP请求来与MailSlurp API进行交互。
首先,你需要在MailSlurp上创建一个账户并获取API密钥。然后,你可以在Flutter项目中使用http
包来发送请求。
-
添加依赖: 在你的
pubspec.yaml
文件中添加http
包的依赖:dependencies: flutter: sdk: flutter http: ^0.13.3 # 请检查最新版本号
-
发送HTTP请求: 创建一个Dart文件(例如
mail_service.dart
),并在其中编写与MailSlurp API交互的代码。import 'dart:convert'; import 'package:http/http.dart' as http; class MailService { final String apiKey; final String apiBaseUrl = 'https://api.mailslurp.com'; MailService({required this.apiKey}); Future<Map<String, dynamic>> createInbox() async { final url = Uri.parse('$apiBaseUrl/inboxes'); final headers = { 'x-api-key': apiKey, 'Content-Type': 'application/json', }; final response = await http.post(url, headers: headers); if (response.statusCode == 201) { return jsonDecode(response.body); } else { throw Exception('Failed to create inbox: ${response.statusCode} ${response.body}'); } } Future<List<Map<String, dynamic>>> getEmails(String inboxId) async { final url = Uri.parse('$apiBaseUrl/inboxes/$inboxId/emails'); final headers = { 'x-api-key': apiKey, 'Content-Type': 'application/json', }; final response = await http.get(url, headers: headers); if (response.statusCode == 200) { return jsonDecode(response.body)['emails'] ?? []; } else { throw Exception('Failed to get emails: ${response.statusCode} ${response.body}'); } } }
-
使用MailService: 在你的主文件(例如
main.dart
)中,使用MailService
来创建收件箱并获取邮件。import 'package:flutter/material.dart'; import 'mail_service.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { late MailService mailService; String? inboxId; List<Map<String, dynamic>> emails = []; @override void initState() { super.initState(); mailService = MailService(apiKey: 'YOUR_API_KEY_HERE'); _createInbox(); } Future<void> _createInbox() async { try { final inbox = await mailService.createInbox(); setState(() { inboxId = inbox['id']; }); _getEmails(); } catch (e) { print(e); } } Future<void> _getEmails() async { try { if (inboxId != null) { final newEmails = await mailService.getEmails(inboxId!); setState(() { emails = newEmails; }); } } catch (e) { print(e); } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('MailSlurp Demo'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ if (inboxId != null) Text('Inbox ID: $inboxId'), Text('Emails:'), Expanded( child: ListView.builder( itemCount: emails.length, itemBuilder: (context, index) { final email = emails[index]; return ListTile( title: Text(email['subject'] ?? 'No Subject'), subtitle: Text(email['from'] ?? 'Unknown Sender'), ); }, ), ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: () => _getEmails(), tooltip: 'Refresh Emails', child: Icon(Icons.refresh), ), ), ); } }
在这个示例中,MailService
类封装了与MailSlurp API交互的逻辑。MyApp
是一个简单的Flutter应用,它使用MailService
来创建一个收件箱并获取其中的邮件。你需要将YOUR_API_KEY_HERE
替换为你从MailSlurp获取的API密钥。
请注意,这个示例代码仅用于演示目的,并未处理所有可能的错误情况。在实际应用中,你可能需要添加更多的错误处理和边界情况检查。