Skip to content

Commit 0154ddf

Browse files
author
Sergey Khomushin
committed
lib code
0 parents  commit 0154ddf

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

lib/api/send_json.dart

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import 'package:http/http.dart' as http;
2+
3+
Future<String> sendJSON(Uri uri, String data) async {
4+
var response = await http.post(
5+
uri,
6+
headers: {
7+
'Content-Type': 'application/json',
8+
},
9+
body: data,
10+
);
11+
12+
if (response.statusCode == 200) {
13+
return response.body;
14+
} else {
15+
throw response.body;
16+
}
17+
}

lib/emailjs.dart

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
library emailjs;
2+
3+
import 'dart:convert';
4+
5+
import 'package:emailjs/utils/validate_params.dart';
6+
import 'package:emailjs/api/send_json.dart';
7+
8+
class EmailJS {
9+
static String _publicKey = '';
10+
static String _origin = 'api.emailjs.com';
11+
12+
static void init(String publicKey, [String? origin]) {
13+
EmailJS._publicKey = publicKey;
14+
EmailJS._origin = origin ?? 'api.emailjs.com';
15+
}
16+
17+
static Future<String> send(
18+
String serviceID,
19+
String templateID, [
20+
Map<String, dynamic>? templatePrams,
21+
String? publicKey,
22+
]) async {
23+
final pubKey = publicKey ?? EmailJS._publicKey;
24+
25+
validateParams(pubKey, serviceID, templateID);
26+
27+
final Map<String, dynamic> params = {
28+
'lib_version': '0.0.1',
29+
'user_id': pubKey,
30+
'service_id': serviceID,
31+
'template_id': templateID,
32+
'template_params': templatePrams,
33+
};
34+
35+
return await sendJSON(
36+
Uri.https(EmailJS._origin, 'api/v1.0/email/send'),
37+
json.encode(params),
38+
);
39+
}
40+
}

lib/utils/validate_params.dart

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
bool validateParams(
2+
String publicKey,
3+
String serviceID,
4+
String templateID,
5+
) {
6+
if (publicKey.isEmpty) {
7+
throw 'The public key is required. Visit https://dashboard.emailjs.com/admin/account';
8+
}
9+
10+
if (serviceID.isEmpty) {
11+
throw 'The service ID is required. Visit https://dashboard.emailjs.com/admin';
12+
}
13+
14+
if (templateID.isEmpty) {
15+
throw 'The template ID is required. Visit https://dashboard.emailjs.com/admin/templates';
16+
}
17+
18+
return true;
19+
}

0 commit comments

Comments
 (0)