Sending emails using app with flutter using SMPT - flutter

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();
}
}
}

Related

Doesn't redirect to current page when logged in with google

#override
Future<UserModel> signInWithGoogle() async {
GoogleSignIn _googleSignIn = GoogleSignIn();
GoogleSignInAccount? _googleUser = await _googleSignIn.signIn();
if(_googleUser != null){
GoogleSignInAuthentication _googleAuth = await _googleUser.authentication;
if(_googleAuth.idToken != null && _googleAuth.accessToken != null){
UserCredential result = await _firebaseAuth.signInWithCredential(
GoogleAuthProvider.credential(idToken: _googleAuth.idToken,accessToken: _googleAuth.accessToken));
return _userFromFirebase(result.user!);
}else{
return null!;
}
}else{
return null!;
}
signInscreen
void _signInGoogle(BuildContext context) async {
final _userViewModel = Provider.of<UserViewModel>(context,listen: false);
UserModel _user = await _userViewModel.signInWithGoogle();
if (_user != null) print("Oturum açan user id:" + _user.userId.toString());
}
SocalIcon(iconSrc: "assets/icons/google-plus.svg",
press: () => _signInGoogle(context),),
When I login with google it is not redirected to current page without clicking back button in emulator. It saves the user to the database, but as I said, I cannot switch to the current page without clicking the back button. What is the reason?

Flutter - Google Sign In uses previously signed in account (user) even after signing out and signing in with another account

When I hit "Sign in with Google", it does let me choose the account although somehow, the previous user gets loaded.
class GoogleSignInProvider extends ChangeNotifier {
GoogleSignIn? _googleSignIn;
GoogleSignInAccount? _user;
GoogleSignInAccount get user => _user!;
bool _isGoogleLogin = false;
final _auth = FirebaseAuth.instance;
Future signInWithGoogle(context) async {
try {
_googleSignIn = GoogleSignIn();
final googleUser = await _googleSignIn!.signIn();
if (googleUser == null) {
return;
}
_user = googleUser;
final googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
var authCredential = await _auth.signInWithCredential(credential);
_isGoogleLogin = true;
if (authCredential.user != null) {
final snapshot = await FirebaseFirestore.instance
.collection('users')
.doc(authCredential.user!.uid)
.get();
if (!snapshot.exists) {
var userId = authCredential.user!.uid;
FirebaseFirestore.instance.collection('users').doc(userId).set({
"email": googleUser.email,
"workoutsCount": 0,
"lastWorkoutDate": null
});
}
}
notifyListeners();
Navigator.of(context).pushNamed('/dashboard');
} on FirebaseAuthException catch (e) {
showSnackBar(context, e);
} catch (e) {
print('ERROR = ');
print(e);
}
}
Future<void> signOut(context) async {
try {
if (_isGoogleLogin) {
final googleCurrentUser =
GoogleSignIn().currentUser ?? await GoogleSignIn().signIn();
if (googleCurrentUser != null) {
await GoogleSignIn().disconnect().catchError((e, stack) {
FirebaseCrashlytics.instance.recordError(e, stack);
});
}
}
await _auth.signOut();
} catch (e) {
showSnackBar(context, e);
} finally {
_isGoogleLogin = false;
Navigator.of(context).pushNamedAndRemoveUntil(
'/register_login', (Route<dynamic> route) => false);
}
}
Is there something wrong with this code??
Can you try to disconnect the account before signing out:
GoogleSignIn _googleSignIn = GoogleSignIn();
await _googleSignIn.disconnect();
await FirebaseAuth.instance.signOut();
You are using firebase auth then please use thsi for signout user :
How to Signout a user in Flutter with Firebase authentication
Remove if (_isGoogleLogin) from your signOut function. googleCurrentUser will check the consitionn and responses based on the result.
First Create a Global variable
FirebaseAuth firebaseAuth = FirebaseAuth.instance;
GoogleSignIn googleSignIn = GoogleSignIn();
Make sure you are using the above variable for login and logout
final googleCurrentUser = firebaseAuth.currentUser;
if (googleCurrentUser != null) {
googleSignIn.signOut();
await firebaseAuth.signOut();
}
User above code for signout user

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);
}
}

How to SignIn with google on Parse Server

I'm developing an application with Flutter and Parse Server and I want to register Users from google account.
I have tried:
static Future<void> loginWithGoogle() async {
try {
final _googleSignIn = GoogleSignIn(scopes: ['email', 'https://www.googleapis.com/auth/contacts.readonly']);
final account = await _googleSignIn.signIn(); // I figure out that the real error is here;
final authentication = await account.authentication;
final googleAuth = google(_googleSignIn.currentUser.id, authentication.accessToken, authentication.idToken);
final response = await ParseUser.loginWith('google', googleAuth);
if (response.success) {
print(response);
//currentUser = await ParseUser.currentUser(customUserObject: User.clone());
//Get.offNamed('/oauth');
}
} catch (e) {
print(e);
AlertUtils.showErrorDialog(e.toString());
}
}
but here I faced that error:
plugin: PlatformException(sign_in_failed,
com.google.android.gms.common.api.ApiException: 10: , null)
You cannot do this without registering on Firebase. The official documentation says so.

Google Authentication and Facebook Authentication Existing User

Hello Everyone someone please offer me some help if you can. I'm not sure if this is an issue on Firebase's side or if I failed on my code or configuring the Firebase authentication correctly.
So here's the issue.
I wanted to see if a user existed inside the firestore. If it does then link the accounts. I read the documentation and understand that when using the SigninwithCredential() it should throw an error saying something on the lines of "ERROR USER ALREADY EXISTS IN FIRESTORE".
So testing went something like this to see if I'd get an error before trying to handle the error.
Continue with Facebook (OK).
Signed In (OK).
Continue with Google (Expected Error) (Didn't throw Error)
So what happened here instead was the user originally created by Facebook was overridden by Google.
Sign In with Facebook (Expected Error) (OK) Recieved error as expected "An Account already exists but with different sign-in credentials"
Read documentation several times and compared google code with Facebook code and can't seem to find answer.
class MyFirebase {
static bool isSignIn = false;
static auth.FirebaseAuth _auth = auth.FirebaseAuth.instance;
static FacebookLogin facebookLogin = FacebookLogin();
static GoogleSignIn googleSignIn = GoogleSignIn();
static Future<auth.User> loginGoogle() async {
final prefs = await SharedPreferences.getInstance();
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
if (googleSignInAccount == null) {
print("ERROR HAS OCCURED WITH THE GOOGLE LOGIN");
throw new Exception("ERROR HAS OCCURED WITH THE LOGIN");
} else {
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
var item = googleSignInAccount.photoUrl;
print("PHOTO URL" + item);
prefs.setString("photoURL", item);
final auth.AuthCredential credential = auth.GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken);
try {
var authResult = await _auth.signInWithCredential(credential);
return authResult.user;
} catch (e) {
print(e);
throw (e);
}
}
}
static Future<auth.User> loginFacebook() async {
final FacebookLoginResult result = await facebookLogin.logIn(['email']);
final prefs = await SharedPreferences.getInstance();
var a;
switch (result.status) {
case FacebookLoginStatus.cancelledByUser:
print("CANCELLED BY USER DO NOT RETURN");
throw new Exception("CANCELLED BY USER DO NOT RETURN");
break;
case FacebookLoginStatus.error:
print("ERROR OCCURED");
throw new Exception("ERROR oCCURED");
break;
case FacebookLoginStatus.loggedIn:
try {
final FacebookAccessToken accessToken = result.accessToken;
auth.AuthCredential credential =
auth.FacebookAuthProvider.credential(accessToken.token);
print("########## MAKING GRAPH RESPONSE");
final response = await http.get(
'https://graph.facebook.com/v2.12/me?fields=name,first_name,picture.width(800).height(800),last_name,email&access_token=${accessToken.token}');
final profile = jsonDecode(response.body);
String item = profile['picture']['data']['url'];
prefs.setString("photoURL", item);
a = await _auth.signInWithCredential(credential);
return a.user;
} catch (e) {
print(e);
throw e;
}
break;
}
return null;
}
static Future<void> signOut() async {
await facebookLogin.logOut();
await _auth.signOut();
await googleSignIn.signOut();
}
}
**strong text** ```