![](/img/trans.png)
[英]How to attach a generated pdf to a smtpjs mail in javascript
[英]How can I use smtpJS to add a self-generated PDF as a mail attachment?
我可以使用smtpJS在我的網站上發送郵件。 但是現在我想附加一個新生成的 PDF ,它是用jsPDF創建的,我嘗試了不同的方法,但它對我不起作用。 有人認出我的問題嗎?
我已在 functions.php 文件中將此鏈接添加到 WordPress。
wp_enqueue_script( 'pdfJS-js', get_stylesheet_directory_uri(). 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js', array( 'jquery' ),'',true );
但是在我的瀏覽器控制台中總是出現以下錯誤:
ReferenceError:找不到變量:jsPDF
( var doc = new jsPDF('p', 'mm', "A4"); )
我的代碼:
function sendMail() {
/* SmtpJS.com - v3.0.0 */
var Email = { send: function (a) { return new Promise(function (n, e) { a.nocache = Math.floor(1e6 * Math.random() + 1), a.Action = "Send"; var t = JSON.stringify(a); Email.ajaxPost("https://smtpjs.com/v3/smtpjs.aspx?", t, function (e) { n(e) }) }) }, ajaxPost: function (e, n, t) { var a = Email.createCORSRequest("POST", e); a.setRequestHeader("Content-type", "application/x-www-form-urlencoded"), a.onload = function () { var e = a.responseText; null != t && t(e) }, a.send(n) }, ajax: function (e, n) { var t = Email.createCORSRequest("GET", e); t.onload = function () { var e = t.responseText; null != n && n(e) }, t.send() }, createCORSRequest: function (e, n) { var t = new XMLHttpRequest; return "withCredentials" in t ? t.open(e, n, !0) : "undefined" != typeof XDomainRequest ? (t = new XDomainRequest).open(e, n) : t = null, t } };
var receiverMail = document.getElementById('email').value;
var doc = new jsPDF('p', 'mm', "A4");
var elementHandler = {
'#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementById("A4")[0];
doc.fromHTML(
source,
297,
210,
{
'width': 210,'elementHandlers': elementHandler
});
var base64 = doc.output("datauristring");
Email.send({
SecureToken : "C973D7AD-F097-4B95-91F4-40ABC5567812",
To : receiverMail,
From : "name@example.com",
Subject : "Offerte von Name",
Body : "tst",
Attachments : [
{
name : "offerte.pdf",
data : base64
}]
}).then(
message => alert(message)
);
}
首先,如果腳本在頁面上,我驗證了jsPDF
作為全局變量加載。 這是。 所以你的問題是腳本沒有加載到頁面上。 這是 PHP 問題,而不是 JS 問題。
問題是 wp_enqueue_script 中的wp_enqueue_script
。 您正在加載遠程站點的 URL,因此它已經是完整的 URL。 您不需要將get_stylesheet_directory_uri()
添加到它。 您在此處的代碼將在 URL 上查找腳本,例如https://mywordpresssite.com/wp-content/themes/my-theme/https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js
這顯然不是你想要的路徑。
wp_enqueue_script(
'pdfJS-js',
get_stylesheet_directory_uri() . 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js',
array( 'jquery' ),
'',
true
);
您可以刪除get_stylesheet_directory_uri().
你應該沒事。 我還添加了一個版本號作為最佳實踐。
wp_enqueue_script(
'pdfJS-js', // handle
'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js', // src
array( 'jquery' ), // dependecies
'1.3.2', // version
true // in footer
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.