2015-02-03 3 views
9

Отправка сообщений электронной почты, похоже, еще не реализована в официальном документе Meteor email package. Я пробовал предложение nodemailer (см. here), но получил сообщение об ошибке «Невозможно прочитать свойство« createTransport »undefined».Отправка вложений электронной почты с помощью Meteor.js (почтовый пакет и/или nodemailer или как-то иначе)

Я пытаюсь создать файл CSV в URI данных, а затем отправить это приложение. Вот отрывок из моего кода при использовании официального пакета электронной почты:

csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv); 

var options = { 
      from: "[email protected]", 
      to: "[email protected]", 
      subject: "xxx", 
      html: html, 
      attachment: { 
      fileName: fileName, 
      path: csvData 
      } 
     }; 

Meteor.call('sendEmail', options); 

EDIT:

Вот в основном то, что мой nodemailer код выглядел так:

var nodemailer = Nodemailer; 
var transporter = nodemailer.createTransport(); 
transporter.sendMail({ 
    from: '[email protected]', 
    to: '[email protected]', 
    subject: 'hello', 
    text: 'hello world!', 
    attachments: [ 
     { 
      path: csvData 
     } 
    ] 
}); 
+0

В чем nodemailer код вы пробовали? Я не считаю, что привязанности поддерживаются в официальном пакете метеора. – rivarolle

+0

Я использовал [этот пакет] (https://atmospherejs.com/mrt/meteor-nodemailer) и следил за инструкциями по его запуску (имеет похожую настройку на электронную почту Meteor). Я обновлю свой вопрос с помощью кода. –

+0

В этой статье приведены некоторые примеры http://kukuruku.co/hub/javascript/meteor-how-to-build-a-todo-list –

ответ

5

Не хватает респ комментировать.

Я решил решить проблему с помощью пакета Sendgrids NPM.

npm install sendgrid 

Если у вас нет npm в вашем приложении метеорита, вы можете прочитать это. https://meteorhacks.com/complete-npm-integration-for-meteor

В вашем packages.json

{ 
    "sendgrid": "1.4.0" 
} 

Затем в файле, который выполняется на сервере:

Meteor.startup(function(){ 
    process.env.MAIL_URL = 'smtp://<username>:<password>@smtp.sendgrid.net:587'; 
}); 

Вот выборочный метод метеор, который получает URL из вложения (мы используя S3) из коллекции вложений. Этот конкретный метод может отправлять любое количество вложений любому количеству получателей. Здесь есть некоторая контекстная специфическая логика, но этого должно быть достаточно, чтобы вы могли запускать отправку вложений.

важная часть:

var email = new sendgrid.Email(); 
email.setFrom("[email protected]"); 
email.setSubject("subject"); 
email.addFile({ 
    filename: attachment_name, 
    url: attachment_url 
}); 
sendgrid.send(email, function (err, json) { 
    if (err) { 
     console.error(err); 
    } 
    if (json) { 
     console.log(json.message);     
    } 
}); 

Полный метод Пример:

Meteor.methods({ 
SendEmail: function (subject, message, templateNumber) { 

    //console.log(subject, message, templateNumber); 

    var user_id = Meteor.userId(); 
    var list = UserList.find({user_id: user_id}).fetch(); 
    var sentTemplate = sentTemplate + templateNumber; 
    var counter = 0; 
    console.log(list.length); 
    // Track is the 'No Response' from the list. 
    for (var i = 0; i < list.length; i++) {  
      var email = new sendgrid.Email(); 
      if (list[i].track == null || list[i].track == "1") { 
       //email.addTo(list[0].list[i].Email); 
       //console.log(list[0].list[i].Email); 
       email.to = list[i].email; 
      } 
      email.setFrom(Meteor.user().email); 
      email.replyto = Meteor.user().email; 

      email.setSubject(subject); 

      var firstName = list[i].name.split(" ")[0]; 

      var companyReplace = message.replace("{{Company}}", list[i].company).replace("{{Company}}", list[i].company).replace("{{Company}}", list[i].company).replace("{{Company}}", list[i].company).replace("{{Company}}", list[i].company); 
      var nameReplace = companyReplace.replace("{{Name}}",list[i].name).replace("{{Name}}",list[i].name).replace("{{Name}}",list[i].name).replace("{{Name}}",list[i].name).replace("{{Name}}",list[i].name) 
      var firstNameReplace = companyReplace.replace("{{FirstName}}",firstName).replace("{{FirstName}}",firstName).replace("{{FirstName}}",firstName).replace("{{FirstName}}",firstName).replace("{{FirstName}}",firstName); 

      email.setHtml(firstNameReplace); 

      var numAttachments = Attachments.find({user_id: Meteor.userId()}).fetch().length; 
      var attachments = Attachments.find({user_id: Meteor.userId()}).fetch(); 
      console.log("**********Attachments****************"); 
      console.log(attachments); 
      console.log("**********Attachments****************"); 
      for (var t = 0; t < numAttachments; t++) { 
       email.addFile({ 
        filename: attachments[t].attachment_name, 
        url: attachments[t].attachment_url 
       }); 
      } 
      sendgrid.send(email, function (err, json) { 
       if (err) { 
        console.error(err); 
       } 
       if (json) { 
        console.log(json.message); 

       } 
      }); 
      //console.log(email); 

    } // end for loop 

    if (templateNumber == 1) { 
     Meteor.users.update({_id:Meteor.userId()}, {$set: {"sentTemplate1": true}}); 
    } 
    if (templateNumber == 2) { 
     Meteor.users.update({_id:Meteor.userId()}, {$set: {"sentTemplate2": true}}); 
    } 
    if (templateNumber == 3) { 
     Meteor.users.update({_id:Meteor.userId()}, {$set: {"sentTemplate3": true}}); 
    } 
    if (templateNumber == 4) { 
     Meteor.users.update({_id:Meteor.userId()}, {$set: {"sentTemplate4": true}}); 
    } 
    // for each email. replace all html 

    return list.length; 
} 
}); 
Смежные вопросы