Created
July 22, 2021 09:06
-
-
Save suragch/f0db66a44c8c5a4ccf50b3869a09f4c1 to your computer and use it in GitHub Desktop.
Email notifications from a Dart server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'dart:io'; | |
import 'package:mailer/mailer.dart'; | |
import 'package:mailer/smtp_server.dart'; | |
Future<void> main() async { | |
final server = await createServer(); | |
print('Server started: ${server.address} port ${server.port}'); | |
await _handleRequests(server); | |
} | |
Future<HttpServer> createServer() async { | |
final address = InternetAddress.loopbackIPv4; | |
const port = 4040; | |
return await HttpServer.bind(address, port); | |
} | |
Future<void> _handleRequests(HttpServer server) async { | |
await for (HttpRequest request in server) { | |
if (request.method == 'POST' && | |
request.uri.path == '/contact') { | |
_handleContactPost(request); | |
} else { | |
_handleBadRequest(request); | |
} | |
} | |
} | |
void _handleBadRequest(HttpRequest request) { | |
request.response | |
..statusCode = HttpStatus.badRequest | |
..write('Bad request') | |
..close(); | |
} | |
Future<void> _handleContactPost(HttpRequest request) async { | |
final body = await utf8.decodeStream(request); | |
final username = 'me@example.com'; | |
final password = 'twRyKjx2Bhf8n3vN'; | |
final smtpServer = SmtpServer( | |
'smtp-relay.sendinblue.com', | |
port: 587, | |
username: username, | |
password: password, | |
); | |
final message = Message() | |
..from = Address(username, 'Suragch') | |
..recipients.add('anotheremail@example.com') | |
..subject = 'New POST message from user' | |
..text = body; | |
int statusCode; | |
try { | |
final sendReport = await send(message, smtpServer); | |
print(sendReport.toString()); | |
statusCode = HttpStatus.ok; | |
} on MailerException catch (e) { | |
print('Message not sent: $e'); | |
statusCode = HttpStatus.internalServerError; | |
} | |
request.response | |
..statusCode = statusCode | |
..close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello, i don't understand that he writes don't use the password directly in the code and you use the password in the code.
end user name = 'me@example.com';
final password = 'twRyKjx2Bhf8n3vN';
lines 39 and 40. I managed to send Emal but for security I don't know how to ensure security. for reminder: please DO NOT use mailer with your credentials. Extracting them is very simple and anyone can then send emails using your account. my host for the server does not allow the use of tokens or hashes to access the email account. HOW TO DO ?