2016-08-02 134 views
1

我只是想直接發送我的html文件,輸入./blabla.html並且不創建廣告系列或模板。有沒有一種方法可以發送郵件而不需要添加嵌入的代碼?如果是這樣,我會非常高興,謝謝! 我當前的代碼如下所示:Sendgrid發送無需嵌入代碼的HTML電子郵件

var helper = require('sendgrid').mail 
 
    from_email = new helper.Email("[email protected]") 
 
    to_email = new helper.Email("[email protected]") 
 
    subject = "Merhaba !" 
 
    content = new helper.Content("text/plain", "selam") 
 
    mail = new helper.Mail(from_email, subject, to_email, content) 
 
} 
 

 
var sg = require('sendgrid').SendGrid("mysecretapikey") 
 
    var requestBody = mail.toJSON() 
 
    var request = sg.emptyRequest() 
 
    request.method = 'POST' 
 
    request.path = '/v3/mail/send' 
 
    request.body = requestBody 
 
    sg.API(request, function (response) { 
 
    console.log(response.statusCode) 
 
    console.log(response.body) 
 
    console.log(response.headers) 
 
    })

+0

爲什麼不能閱讀HTML文件轉換成字符串像這樣:http://stackoverflow.com/questions/18386361/read-a-file-in-node-js?另外請注意,如果你想以HTML的形式發送,你會希望爲'content'設置'text/html'。 –

+0

沒關係,但我無法找到放置該讀取操作的位置。當我調用讀取函數時,它只是讀取cmd上的內容並將郵件發送給寫入函數名稱的接收方。任何幫助? @ Sebastian-LaurenţiuPlesciuc – MeganLondon

回答

2

您可能需要更新您的sendgrid包。根據您的要求的工作的例子看起來是這樣的:

var fs = require('fs'); 
var path = require('path'); 

var filePath = path.join(__dirname, 'myfile.html'); 

fs.readFile(filePath, {encoding: 'utf-8'}, function(err, data) { 
    if (! err) { 
     var helper = require('sendgrid').mail; 
     from_email = new helper.Email("[email protected]"); 
     to_email = new helper.Email("[email protected]"); 
     subject = "Merhaba !"; 
     content = new helper.Content("text/html", data); 
     mail = new helper.Mail(from_email, subject, to_email, content); 

     var sg = require('sendgrid')('your api key'); 
     var requestBody = mail.toJSON(); 
     var request = sg.emptyRequest(); 
     request.method = 'POST'; 
     request.path = '/v3/mail/send'; 
     request.body = requestBody; 
     sg.API(request, function (error, response) { 
     if (! error) { 
      console.log(response.statusCode); 
      console.log(response.body); 
      console.log(response.headers); 
     } else { 
      console.log(error); 
     } 
     }); 
    } else { 
     console.log(err); 
    } 
}); 

myfile.html文件旁邊就是這個.js文件看起來是這樣的:

<html> 
<head> 
    <title> Test </title> 
</head> 
<body> 
    <h2> Hi! </h2> 
    <p> This is a test email </p> 
</body> 
</html> 
+0

謝謝!這個真的很感謝你! – MeganLondon

相關問題