How to send email from a Flutter Web application? - email

I'm trying to send email from a Flutter Web application using mailer package but I'm getting this error:
Unsupported operation: Socket constructor
It seems like the package is dependent on dart:io which is not supported on Flutter Web. This is the the code that is meant to send email:
_sendEmail(String body) async {
print('Sending email...');
String username = 'myemail';
String password = 'mypassword';
final smtpServer = gmail(username, password);
final message = Message()
..from = Address(username, 'sender_name')
..recipients.add('reciever_email')
..subject = 'subject'
..text = body;
try {
final sendReport = await send(message, smtpServer);
print('message sent: ${sendReport.toString()}');
} catch (e) {
print('message not sent: $e');
e.problems.forEach(
(element) => print('Problem: ${element.code}: ${element.msg}')
);
}
I've used placeholders for credentials and I'm sure they're correct. Is there a way to send email from Flutter Web application?

Related

Sending emails using app with flutter using SMPT

I have tried to send emails using app, that app is built using flutter framework. There is no error while it is running but emails are not sent. This is my code.
**send email function**
Future sendEmail(subject,msg) async{
final user = await GoogleAuthApi.signIn();
if(user == null) return;
final email = user.email;
final auth = await user.authentication;
final token =auth.accessToken!;
final smtpServer = gmailRelaySaslXoauth2(email, token);
final message = Message()
..from = Address(email,'test')
..recipients = ["test#gmail.com"]
..subject = subject.toString()
..text=msg.toString();
try{
await send(message,smtpServer);
showSnackBar('Sent email successfully!');
}on MailerException catch(e){
print("hi==$e");
}
}
class GoogleAuthApi{
static final _googleSignIn = GoogleSignIn(scopes: ['https://mail.google.com/']);
static Future<GoogleSignInAccount?> signIn() async{
if(await _googleSignIn.isSignedIn()){
return _googleSignIn.currentUser;
}else {
return await _googleSignIn.signIn();
}
}
}

send email to current user email in flutter

In this code send email to specific email but I want send email to current user email
I connect my project with firebase.
sendMail() async {
String username = 'example#gmail.com';
String password = 'axneqgkraxm';
final smtpServer = gmail(username, password);
final message = Message()
..from = Address(username, 'testing')
..recipients.add('uu500oi#gmail.com')
..subject = 'Receipt :: ${DateTime.now()}'
..text = 'This is the plain text.\nThis is line 2 of the text part.'
..html = html
.replaceFirst('{{title}}', 'this will be the title')
.replaceFirst('{{price}}', '20')
.replaceFirst('{{hours}}', '2:00 PM')
.replaceFirst('{{description}}', 'this is description');
try {
final sendReport = await send(message, smtpServer);
print('Message sent: ' + sendReport.toString());
} on MailerException catch (e) {
print(e);
print('Message not sent.');
for (var p in e.problems) {
print('Problem: ${p.code}: ${p.msg}');
}
}
anyone can solve it???
Try the following code:
sendMail() async {
if (FirebaseAuth.instance.currentUser != null) {
String username = 'example#gmail.com';
String password = 'axneqgkraxm';
final smtpServer = gmail(username, password);
final message = Message()
..from = Address(username, 'testing')
..recipients.add(FirebaseAuth.instance.currentUser?.email)
..subject = 'Receipt :: ${DateTime.now()}'
..text = 'This is the plain text.\nThis is line 2 of the text part.'
..html = html
.replaceFirst('{{title}}', 'this will be the title')
.replaceFirst('{{price}}', '20')
.replaceFirst('{{hours}}', '2:00 PM')
.replaceFirst('{{description}}', 'this is description');
try {
final sendReport = await send(message, smtpServer);
print('Message sent: ' + sendReport.toString());
} on MailerException catch (e) {
print(e);
print('Message not sent.');
for (var p in e.problems) {
print('Problem: ${p.code}: ${p.msg}');
}
}
}
}
You can get the email address of the current user from Firebase Authentication with:
if (FirebaseAuth.instance.currentUser != null) {
print(FirebaseAuth.instance.currentUser?.email);
}
Also see the Firebase documentation on getting the current user profile and the reference document for Firebase's User object.

How to Sending sms and email using Dart (Flutter)?

I am trying to build and app in flutter which sends email and SMS. Purpose is to reset password (forgot Password). But I am not able to find a suitable package for it. The email or SMS should be sent with out user interaction once they click reset password. The SMS and email will be sent from their mobile to the very same number or email.
Any alternate suggestions?
For Email, you can use this mailer package => https://pub.dev/packages/mailer
Update:
If this function didn't work then lower your mailer package version.
Example:
Future<void> sendMail(String name, String otp, String recipientEmail) async {
// ignore: deprecated_member_use
SmtpServer smtpServer = gmail('yourEmail', 'Password');
Message message = Message()
..from = address('yourEmail', 'UserName')
..recipients.add(recipientEmail)
..subject = 'Any Text.'
..html = "Any Text.";
try {
final sendReport = await send(message, smtpServer);
PrintLog.printMessage('Message sent: ' + sendReport.toString());
} on MailerException catch (e) {
PrintLog.printMessage('Message not sent. ' + e.toString());
for (var p in e.problems) {
PrintLog.printMessage('Problem: ${p.code}: ${p.msg}');
}
}
var connection = PersistentConnection(smtpServer);
await connection.send(message);
await connection.close();
}
For SMS, you can use Url Launcher Package => https://pub.dev/packages/url_launcher
Example:
_textMe() async {
if (Platform.isAndroid) {
const uri = 'sms:YourNumber?body=hello%20there';
await launch(uri);
} else if (Platform.isIOS) {
// iOS
const uri = 'sms:YourNumber&body=hello%20there';
await launch(uri);
}
}

Getting incorrect username and password exception by using `gmailSaslXoauth2`

I am using mailer package from dart pub. I created a service account and copied the content of json file into class variable CLIENT_JSON. You can see some fields of CLIENT_JSON in getAccessToken() function.
Whenever I try to email someone, an exception is thrown
SmtpClientAuthenticationException (Incorrect username / password / credentials)
Here are two functions I am calling from UI.
Future<AccessCredentials> getAccessToken() async {
var accountCredentials = ServiceAccountCredentials.fromJson({
"private_key_id": CLIENT_JSON["private_key_id"],
"private_key": CLIENT_JSON["private_key"],
"client_email": CLIENT_JSON["client_email"],
"client_id": CLIENT_JSON['client_id'],
"type": "service_account"
});
AccessCredentials accessCredentials;
final client = http.Client();
try {
accessCredentials = await obtainAccessCredentialsViaServiceAccount(
accountCredentials, ["https://mail.google.com/"], client);
print("[EMAIL_SERVICE] Access Token Fetched");
} on Exception catch (err) {
print("[EMAIL_SERVICE] Error in fetching access token. Error: $err");
}
client.close();
return accessCredentials;
}
Future<void> sendEmailFromConfibuddy({
#required String receiverEmail,
#required String subject,
#required String body,
}) async {
final credentials = await getAccessToken();
if (credentials == null) {
print("[EMAIL_SERVICE] Credentials are null.");
return;
}
final smtpServer = gmailSaslXoauth2(
CLIENT_JSON["client_email"], credentials.accessToken.data);
final message = Message()
..from = Address(CLIENT_JSON["client_email"], 'Confibuddy')
..recipients.add("example#gmail.com")
..subject = subject
..html = body;
try {
final sendReport = await send(message, smtpServer);
print('Message sent: ' + sendReport.toString());
} on MailerException catch (e) {
print('Message not sent.');
for (var p in e.problems) {
print('Problem: ${p.code}: ${p.msg}');
}
}
}
}
Right now, I can generate an access token using the googleapis_auth package. But I am confused about which email to put in the gmailSaslXoauth2 function as the userEmail parameter. I have two emails, one is my personal account in which I created the project and created a service account and an email generated in json file named as client_email.
client_email looks like this example#example.iam.gserviceaccount.com.

Flutter mailer is sending duplicate emails, two at the same time

I have to build an app with a send email function and i decided to use mailer. But after testing I get two identical emails and I put one more email to cc and that email also received two emails. Is there a way so that my app will send only one email and not two?
void _mailer() async {
String username = '**#gmail.com';
String password = '**';
final smtpServer = gmail(username, password);
final message = Message()
..from = Address(username, 'Your name')
..recipients.add('**#outlook.com')
..ccRecipients.add('**#yahoo.com')
..subject = 'Test Dart Mailer library :: 😀 :: ${DateTime.now()}'
..text = 'This is the plain text.\nThis is line 2 of the text part.'
..attachments = attachments;
try {
final sendReport = await send(message, smtpServer);
print('Message sent: ' + sendReport.toString());
} on MailerException catch (e) {
print('Message not sent.');
for (var p in e.problems) {
print('Problem: ${p.code}: ${p.msg}');
}
}
var connection = PersistentConnection(smtpServer);
await connection.send(message);
await connection.close();
}
It seems that this function sends 1 email:
try {
final sendReport = await send(message, smtpServer);
print('Message sent: ' + sendReport.toString());
} on MailerException catch (e) {
print('Message not sent.');
for (var p in e.problems) {
print('Problem: ${p.code}: ${p.msg}');
}
}
And these 3 lines of code are sending the second email:
var connection = PersistentConnection(smtpServer);
await connection.send(message);
await connection.close();
So I just deleted the last 3 lines of code and now my app is sending just one email