Reputation: 41
This gives you logged in user's email address via accounts-password.
Meteor.user().emails[0].address
How can I get email addresses on the client/server when users use third party services to login? E.g. facebook, google.
I want to call the following method from the client
Meteor.methods({
sendEmail: function() {
var userEmail;
if(Meteor.user().emails[0].address) {
return userEmail = Meteor.user().emails[0].address;
} else if (Meteor.user().services.google.email) {
return userEmail = Meteor.user().services.google.email;
} else if (Meteor.user().services.facebook.email) {
return userEmail = Meteor.user().services.facebook.email;
}
Email.send({
to: userEmail,
from: "[email protected]",
subject: "some subject",
text: "sometext"
});
}
});
I get TypeError: Cannot read property '0' of undefined
Upvotes: -1
Views: 487
Reputation: 95
Meteor.call('sendEmail', function(error) {
if (error) {
if (error.error === 'user-not-found') {
console.log('Error: User not found');
} else if (error.error === 'email-not-found') {
console.log('Error: User email not found');
} else {
console.log('Error sending email:', error);
}
} else {
console.log('Email sent successfully');
}
});
It will work like a charm in your case
Upvotes: 0
Reputation: 41
I don't like this but it works this way
Meteor.methods({
sendEmail: function() {
this.unblock();
var currentUser = Meteor.user();
if (currentUser && currentUser.emails && currentUser.emails[0]
&& currentUser.emails[0].address) {
var userEmail = currentUser.emails[0].address;
Email.send({
to: userEmail,
from: "[email protected]",
subject: "something",
text: "something"
});
} else if (currentUser && currentUser.services && currentUser.services.google
&& currentUser.services.google.email) {
var userEmail = currentUser.services.google.email;
Email.send({
to: userEmail,
from: "[email protected]",
subject: "something",
text: "something"
});
} else if (currentUser && currentUser.services && currentUser.services.facebook
&& currentUser.services.facebook.email) {
var userEmail = currentUser.services.facebook.email;
Email.send({
to: userEmail,
from: "[email protected]",
subject: "something",
text: "something"
});
}
}
});
I think it just assumes that it can send an email to empty string/null/undefined. I tried to throw Meteor.Error on if(!userEmail)
no luck. If someone can make this code neater I'd appreciate it.
Upvotes: 0