var SITE_URL = Meteor.absoluteUrl();
function sendEmailNotification(type, sourceUser, recipients, notificationObject) {
var emailFrom = 'server@example.com';
var emailSubject = 'MyApp: ';
var emailBody = '';
$.each(recipients, function (index, recipient) {
recipients[index] = recipient + '@example.com';
});
switch(type) {
case 'item_assigned':
emailSubject += notificationObject.item_title;
emailBody += '<div style="padding:10px;">';
emailBody += sourceUser;
emailBody += ' has assigned you an action item';
emailBody += '</div>'
break;
case 'list_shared':
emailSubject += notificationObject.list_title;
emailBody += '<div style="padding:10px;">';
emailBody += sourceUser;
emailBody += ' has shared a list with you: ';
emailBody += '<a href="' + SITE_URL + '#' + notificationObject.list_id + '">' + notificationObject.list_title + '</a>';
emailBody += '</div>'
break;
}
if (Meteor.isServer) {
// This function only runs on server
Email.send({
from: emailFrom,
bcc: recipients,
subject: emailSubject,
html: emailBody
});
}
}
以上函数位于根目录中的JS文件中(因此其代码可供客户端和服务器使用)。但是当我在我的客户端代码中调用它时,没有任何反应。我的应用中包含email
个包。在我的本地计算机(Windows 7)上,我没有设置MAIL_URL
变量。因此,调用Email.send()
函数最好在命令提示符下生成输出,但实际上没有输出。
在我们的生产服务器上,SMTP已正确设置,其他应用程序可以发送具有相同设置的电子邮件。我已经在那里正确配置了MAIL_URL
环境变量,但仍然没有发送电子邮件。
有人可以告诉我我的代码是否有问题?我有什么不正确的吗?
P.S。:我甚至尝试直接调用Email.send(),如下面的代码所示,但仍然没有发生任何事情。
if (Meteor.isServer) {
Email.send({
from: 'server@example.com',
to: 'my-gmail-id@gmail.com',
subject: 'This is a test email',
html: '<b>Congrats, it works!</b>'
});
}
}
});
答案 0 :(得分:3)
几乎是Meteor's Email is undefined
的副本请参阅this pull request了解示例代码。
只是为了澄清:Meteor不按顺序执行客户端和服务器代码。您必须更明确地了解客户端与服务器上运行的内容。不要考虑JavaScript页面上的线性执行,而是认为每个Meteor代码都是作为事件的结果运行的。如果某段代码没有运行,那是因为没有事件触发它。
答案 1 :(得分:0)
我通过使用Meteor.methods
创建服务器端方法并将上面的整个代码放入其中来解决它。
var SITE_URL = Meteor.absoluteUrl();
Meteor.methods({
sendEmailNotification: function (type, sourceUser, recipients, notificationObject) {
if (recipients.length > 0) {
var emailFrom = 'app@example.com';
var emailSubject = 'MyApp: ';
var emailBody = '';
for (var i = 0; i < recipients.length; i++) {
recipients[i] = recipients[i] + '@example.com';
}
switch (type) {
case 'item_assigned':
emailSubject += notificationObject.item_title;
emailBody += '<div style="padding:10px;">';
emailBody += sourceUser;
emailBody += ' has assigned you an action item';
emailBody += '</div>'
break;
case 'list_shared':
emailSubject += notificationObject.list_title;
emailBody += '<div style="padding:10px;">';
emailBody += sourceUser;
emailBody += ' has shared a list with you: ';
emailBody += '<a href="' + SITE_URL + '#' + notificationObject.list_id + '">' + notificationObject.list_title + '</a>';
emailBody += '</div>'
break;
}
Email.send({
from: emailFrom,
bcc: recipients,
subject: emailSubject,
html: emailBody
});
}
}
});
要在客户端代码中调用上述函数,请使用:
Meteor.call('sendEmailNotification', 'list_shared', Meteor.user().username, [sharedUserName], listDetails);