Flutter邮件发送插件emailjs的使用

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

Flutter邮件发送插件emailjs的使用

官方EmailJS SDK for Flutter

SDK适用于EmailJS.com用户。
使用您的EmailJS账户发送邮件。

免责声明

这是仅限Flutter版本的SDK,其他平台请使用:

链接

简介

EmailJS帮助您直接从代码中发送邮件。无需服务器——只需将EmailJS连接到支持的邮件服务之一,创建一个邮件模板,并使用我们的SDK触发邮件。

使用方法

安装EmailJS SDK:

$ flutter pub add emailjs 

注意:默认情况下,非浏览器应用程序的API请求被禁用。您需要通过Account:Security激活它们。

常见问题解答

API调用对非浏览器应用程序已禁用

您需要通过Account:Security激活API请求。

示例

发送邮件

import 'package:emailjs/emailjs.dart' as emailjs;

Map<String, dynamic> templateParams = {
  'name': 'James',
  'notes': 'Check this out!'
};

try {
  await emailjs.send(
    'YOUR_SERVICE_ID',
    'YOUR_TEMPLATE_ID',
    templateParams,
    const emailjs.Options(
      publicKey: 'YOUR_PUBLIC_KEY',
      privateKey: 'YOUR_PRIVATE_KEY',
    ),
  );
  print('SUCCESS!');
} catch (error) {
  print('$error');
}

初始化(可选)

import 'package:emailjs/emailjs.dart' as emailjs;

// 设置公共密钥为全局设置
emailjs.init(const emailjs.Options(
  publicKey: 'YOUR_PUBLIC_KEY',
  privateKey: 'YOUR_PRIVATE_KEY',
));

try {
  // 发送邮件时不需要动态变量
  await emailjs.send(
    'YOUR_SERVICE_ID',
    'YOUR_TEMPLATE_ID',
  );
  print('SUCCESS!');
} catch (error) {
  print('$error');
}

完整示例Demo

以下是一个完整的Flutter应用示例,展示了如何在Flutter应用中集成和使用emailjs插件来发送邮件:

import 'package:flutter/material.dart';
import 'package:emailjs/emailjs.dart' as emailjs;

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo EmailJS',
      theme: ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: const HomePage(title: 'Flutter Demo EmailJS'),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key, required this.title});
  final String title;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  void _sendEmail() async {
    try {
      await emailjs.send(
        'YOUR_SERVICE_ID', // 替换为您自己的服务ID
        'YOUR_TEMPLATE_ID', // 替换为您自己的模板ID
        {
          'to_email': 'hi@example.com', // 收件人邮箱地址
          'message': 'Hi', // 邮件内容
        },
        const emailjs.Options(
            publicKey: 'YOUR_PUBLIC_KEY', // 替换为您自己的公共密钥
            privateKey: 'YOUR_PRIVATE_KEY', // 替换为您自己的私有密钥
            limitRate: const emailjs.LimitRate(
              id: 'app',
              throttle: 10000,
            )),
      );
      print('SUCCESS!');
    } catch (error) {
      if (error is emailjs.EmailJSResponseStatus) {
        print('ERROR... $error');
      }
      print(error.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'Press "Send Email" to send email',
            ),
            ElevatedButton(
              onPressed: _sendEmail,
              child: const Text('Send Email'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用程序,其中包含一个按钮,点击该按钮后会尝试发送一封邮件。请确保替换所有的占位符(如YOUR_SERVICE_IDYOUR_TEMPLATE_ID等)为您自己的实际值。此外,确保在EmailJS的账户设置中启用了非浏览器应用程序的API请求。


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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用emailjs插件来发送邮件的示例代码。需要注意的是,emailjs是一个流行的JavaScript库,但直接在Flutter中使用可能需要一些桥接工作,因为Flutter主要是基于Dart语言的。然而,我们可以使用Flutter的WebView或Platform Channels来与JavaScript交互。

由于Flutter没有直接的emailjs插件,这里我将展示如何通过Platform Channels与原生Android或iOS代码交互,并在原生代码中调用emailjs

1. 设置Flutter项目

首先,创建一个新的Flutter项目:

flutter create emailjs_example
cd emailjs_example

2. 添加Platform Channels

在Flutter中定义MethodChannel

lib目录下,打开main.dart文件,并添加以下代码来定义与原生代码通信的MethodChannel:

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

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

class MyApp extends StatelessWidget {
  static const platform = MethodChannel('com.example.emailjs_example/channel');

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

  Future<void> _sendEmail() async {
    try {
      final String result = await platform.invokeMethod('sendEmail', {
        'userId': 'your-emailjs-user-id',
        'serviceId': 'your-emailjs-service-id',
        'templateId': 'your-emailjs-template-id',
        'templateParams': {
          'name': 'John Doe',
          'message': 'Hello, this is a test email!'
        },
      });

      print("Email sent: $result");
    } on PlatformException catch (e) {
      print("Failed to send email: '${e.message}'.");
    }
  }
}

在Android中处理MethodChannel

android/app/src/main/kotlin/.../MainActivity.kt(如果你使用的是Kotlin)中添加以下代码:

package com.example.emailjs_example

import android.os.Bundle
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import org.json.JSONObject
import org.web3j.protocol.http.HttpService
import okhttp3.*

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.example.emailjs_example/channel"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "sendEmail") {
                val arguments = call.argument<Map<String, Any>>("arguments")
                val userId = arguments?.get("userId") as String
                val serviceId = arguments?.get("serviceId") as String
                val templateId = arguments?.get("templateId") as String
                val templateParams = arguments?.get("templateParams") as Map<String, String>

                sendEmail(userId, serviceId, templateId, templateParams) { success, message ->
                    if (success) {
                        result.success(message)
                    } else {
                        result.error("UNAVAILABLE", message, null)
                    }
                }
            } else {
                result.notImplemented()
            }
        }
    }

    private fun sendEmail(userId: String, serviceId: String, templateId: String, templateParams: Map<String, String>, callback: (Boolean, String) -> Unit) {
        val url = "https://api.emailjs.com/api/v1.0/email/send"
        val json = JSONObject()
        json.put("user_id", userId)
        json.put("service_id", serviceId)
        json.put("template_id", templateId)
        json.put("template_params", JSONObject(templateParams.toMap()))

        val body = RequestBody.create(
            MediaType.parse("application/json; charset=utf-8"),
            json.toString()
        )

        val request = Request.Builder()
            .url(url)
            .post(body)
            .addHeader("Authorization", "Bearer your-emailjs-public-api-key")
            .build()

        val client = OkHttpClient()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback(false, "Failed to send email: ${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    callback(true, "Email sent successfully!")
                } else {
                    callback(false, "Failed to send email: ${response.message()}")
                }
            }
        })
    }
}

在iOS中处理MethodChannel

ios/Runner/AppDelegate.swift中添加以下代码:

import UIKit
import Flutter

[@UIApplicationMain](/user/UIApplicationMain)
[@objc](/user/objc) class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let channel = FlutterMethodChannel(name: "com.example.emailjs_example/channel", binaryMessenger: controller)
    
    channel.setMethodCallHandler({
      (call: FlutterMethodCall, result: [@escaping](/user/escaping) FlutterResult) in
      
      guard let arguments = call.arguments as? [String: Any],
            let userId = arguments["userId"] as? String,
            let serviceId = arguments["serviceId"] as? String,
            let templateId = arguments["templateId"] as? String,
            let templateParams = arguments["templateParams"] as? [String: String] else {
        result(FlutterError(code: "UNAVAILABLE", message: "Invalid arguments", details: nil))
        return
      }
      
      sendEmail(userId: userId, serviceId: serviceId, templateId: templateId, templateParams: templateParams) { success, message in
        if success {
          result(message)
        } else {
          result(FlutterError(code: "UNAVAILABLE", message: message, details: nil))
        }
      }
    })
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  private func sendEmail(userId: String, serviceId: String, templateId: String, templateParams: [String: String], completion: [@escaping](/user/escaping) (Bool, String) -> Void) {
    let urlString = "https://api.emailjs.com/api/v1.0/email/send"
    let parameters: [String: Any] = [
      "user_id": userId,
      "service_id": serviceId,
      "template_id": templateId,
      "template_params": templateParams
    ]
    
    guard let url = URL(string: urlString) else {
      completion(false, "Invalid URL")
      return
    }
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("Bearer your-emailjs-public-api-key", forHTTPHeaderField: "Authorization")
    request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
    
    let session = URLSession.shared
    let task = session.dataTask(with: request) { data, response, error in
      guard let data = data, error == nil else {
        completion(false, "Failed to send email: \(String(describing: error))")
        return
      }
      
      do {
        let jsonResponse = try JSONSerialization.jsonObject(with: data, options: [])
        if let dict = jsonResponse as? [String: Any], let status = dict["status"] as? String, status == "200" {
          completion(true, "Email sent successfully!")
        } else {
          completion(false, "Failed to send email: Invalid response")
        }
      }
回到顶部