كيفية إرسال بريد إلكتروني باستخدام Gmail API وNode.js

في برنامج تعليمي سابق، استخدمنا حساب خدمة للاتصال بـ Google Drive API من تطبيق Node.js. لا يمكننا استخدام حساب خدمة لانتحال شخصية حساب Gmail، ولكن يمكننا استخدام واجهة برمجة تطبيقات GMail مع Node.js وNodemailer لإرسال رسائل البريد الإلكتروني من حساب Gmail أو Google Workspace الخاص بالمستخدم.
ومع ذلك، يمكنك استخدام خدمات خارجية، مثل Amazon’s SES أو SendGrid من Twilio، لإرسال رسائل البريد الإلكتروني من حساب الخدمة.
في هذا البرنامج التعليمي، سنصف كيفية إرسال رسائل البريد الإلكتروني من حساب Gmail باستخدام GMail API وتطبيق Node.js. يرجى ملاحظة أن Gmail يفرض حدًا للإرسال يبلغ 2000 رسالة يوميًا بحد إجمالي يبلغ 10000 مستلم يوميًا. تتم إعادة تعيين حصة البريد الإلكتروني في منتصف الليل بتوقيت المحيط الهادئ تلقائيًا.
1. قم بإنشاء مشروع Google Cloud
اذهب الى cloud.google.com
وإنشاء مشروع Google Cloud جديد. قم بتسمية مشروعك، وقم بتغيير معرف المشروع وانقر فوق Create
زر.
2. تمكين واجهات برمجة تطبيقات Google
يختار APIs & Services
من القائمة اليسرى ثم اضغط على Enable APIs and Services
لتمكين واجهة برمجة تطبيقات Gmail. تتيح لك واجهة برمجة تطبيقات Gmail عرض وإدارة بيانات صندوق بريد Gmail مثل سلاسل الرسائل والرسائل والتسميات.
3. تكوين شاشة موافقة OAuth
تحت APIs and Services
القسم، انقر على OAuth Consent Screen
وقم بتعيين نوع المستخدم كـ Internal
. سيسمح هذا للتطبيق بالوصول إلى Gmail API دون الحاجة إلى إجراء عملية التحقق الشاملة من OAuth والتي قد تستغرق عدة أسابيع. انقر فوق Save and Continue
.
4. نطاقات OAuth 2.0
في شاشة الموافقة، أدخل اسمًا لتطبيقك وقدم عنوان بريدك الإلكتروني حيث يمكن لشركة Google الاتصال بك إذا كانت هناك أي تغييرات على شاشة الموافقة.
في الشاشة التالية، يتعين عليك توفير نطاق OAuth 2.0 واحد أو أكثر لواجهات برمجة تطبيقات Google. انقر فوق Add Or Remove Scopes
زر وإضافة https://www.googleapis.com/auth/gmail.send
إلى قائمة النطاقات لأننا نريد فقط إرسال رسائل البريد الإلكتروني من Gmail وعدم قراءة أي بيانات للمستخدم. انقر Save and Continue
.
4. قم بإنشاء عميل Gmail OAuth
في APIs & Services
القسم، انقر على Credentials
وانقر على Create credentials
> OAuth Client Id
لإنشاء معرف عميل جديد سيتم استخدامه لتعريف تطبيقك على خوادم OAuth الخاصة بـ Google.
4. نوع التطبيق
اضبط نوع التطبيق على Desktop App
، قم بتسمية عميل OAuth الخاص بك ثم انقر فوق Create
لإنشاء بيانات الاعتماد. يتم استخدام اسم عميل OAuth 2.0 الخاص بك فقط لتحديد العميل في وحدة تحكم Google Cloud ولن يتم عرضه لمستخدمي التطبيق.
انقر فوق Download JSON
زر لتنزيل بيانات الاعتماد على جهاز الكمبيوتر الخاص بك. يوصى باستخدام متغيرات بيئة Node لتخزين بيانات الاعتماد الخاصة بك وعدم إرسال هذا الملف إلى مستودع Github الخاص بك.
{
"installed": {
"client_id": "4181097263-eqfdl92e3r.apps.googleusercontent.com",
"project_id": "developer-playground",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "GOCSPX-KW_5UbfcvCW9LeNsO-gD7T",
"redirect_uris": ["http://localhost"]
}
}
5. الحصول على رمز التفويض
يبدأ تسلسل تفويض OAuth عندما يعيد تطبيقك توجيه المستخدم إلى عنوان URL الخاص بـ Google والذي يحتوي على معرف عميل OAuth والنطاقات المطلوبة. تتعامل Google مع مصادقة المستخدم وتعيد رمز التفويض، والذي يمكن للتطبيق استبداله برمز وصول ورمز تحديث.
// auth.js
const { google } = require('googleapis');
const credentials = require('./credentials.json');
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
const GMAIL_SCOPES = ['https://www.googleapis.com/auth/gmail.send'];
const url = oAuth2Client.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: GMAIL_SCOPES
});
console.log('Authorize this app by visiting this url:', url);
افتح موجه الأوامر الخاص بك وقم بتشغيل الأمر التالي. ستتم إعادة توجيهك إلى صفحة تفويض Google.
$ node auth.js
Authorize this app by visiting this url:
https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.send&response_type=code&client_id=4181097263-eqfdl92e3r.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost
6. قم بإنشاء عميل OAuth2 معتمد
يقوم المتصفح بإنشاء رمز تفويض يمكنك لصقه فيه token.js
لإنشاء رمز وصول ورمز تحديث. سيكون رمز الوصول صالحًا لمدة ساعة واحدة وسيستخدم التطبيق رمز التحديث للحصول على رمز وصول جديد عند انتهاء صلاحيته.
// token.js
const { google } = require('googleapis');
const path = require('path');
const fs = require('fs');
const credentials = require('./credentials.json');
// Replace with the code you received from Google
const code = '4/0AX4XfWjz8e2q81iC9TFzgHCn1tdTmQyMjA';
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
oAuth2Client.getToken(code).then(({ tokens }) => {
const tokenPath = path.join(__dirname, 'token.json');
fs.writeFileSync(tokenPath, JSON.stringify(tokens));
console.log('Access token and refresh token stored to token.json');
});
قم بتشغيل الأمر التالي لإنشاء رمز الوصول ورمز التحديث.
$ node token.js
Access token and refresh token stored to token.json
وهذا سيضيف جديدا token.json
ملف إلى دليل المشروع الخاص بك الذي يحتوي على رمز الوصول ورمز التحديث.
{
"access_token": "ya29.A0ARrdaM_AaAL3mdEpVZshT-cFfpLkxeMOJz_d1Ok",
"refresh_token": "1//0gdubhqQhx89VVNBR45_4eipxlYc4Nf5A9J67B8M",
"scope": "https://www.googleapis.com/auth/gmail.send",
"token_type": "Bearer",
"expiry_date": 1649574729833
}
7. مكتبة مرسل البريد الإلكتروني
نحن نستخدم مكتبة Nodemailer الشهيرة لإنشاء رسائل بريد إلكتروني بتنسيق RFC822 يمكن دفقها إلى SMTP. يمكنك أيضًا إنشاء رسالة Mime يدويًا ولكن الأولى أسهل في الاستخدام.
// gmail.js
const { google } = require('googleapis');
const MailComposer = require('nodemailer/lib/mail-composer');
const credentials = require('./credentials.json');
const tokens = require('./tokens.json');
const getGmailService = () => {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
oAuth2Client.setCredentials(tokens);
const gmail = google.gmail({ version: 'v1', auth: oAuth2Client });
return gmail;
};
const encodeMessage = (message) => {
return Buffer.from(message).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
};
const createMail = async (options) => {
const mailComposer = new MailComposer(options);
const message = await mailComposer.compile().build();
return encodeMessage(message);
};
const sendMail = async (options) => {
const gmail = getGmailService();
const rawMessage = await createMail(options);
const { data: { id } = {} } = await gmail.users.messages.send({
userId: 'me',
resource: {
raw: rawMessage
}
});
return id;
};
module.exports = sendMail;
8. إرسال البريد الإلكتروني باستخدام Gmail API
هذه هي الخطوة الأخيرة. قم بإنشاء كائن mailOptions الذي يحدد الحقول المختلفة للرسالة بما في ذلك اسم المرسل والمستلمين والمرفقات ونص HTML والموضوع. يمكنك أيضًا إضافة رؤوس إلى الرسالة، وهي مفيدة لإضافة معلومات تتبع الرسالة.
بالنسبة لمرفقات الملفات، يمكنك إرفاق أي ملف مباشرة من نظام الملفات المحلي برسالة Gmail أو حتى سحب مرفق من عنوان URL بعيد.
const fs = require('fs');
const path = require('path');
const sendMail = require('./gmail');
const main = async () => {
const fileAttachments = [
{
filename: 'attachment1.txt',
content: 'This is a plain text file sent as an attachment'
},
{
path: path.join(__dirname, './attachment2.txt')
},
{
filename: 'websites.pdf',
path: 'https://www.labnol.org/files/cool-websites.pdf'
},
{
filename: 'image.png',
content: fs.createReadStream(path.join(__dirname, './attach.png'))
}
];
const options = {
to: 'amit@labnol.org',
cc: 'cc1@example.com, cc2@example.com',
replyTo: 'amit@labnol.org',
subject: 'Hello Amit 🚀',
text: 'This email is sent from the command line',
html: `<p>🙋🏻♀️ — This is a <b>test email</b> from <a href="https://digitalinspiration.com">Digital Inspiration</a>.</p>`,
attachments: fileAttachments,
textEncoding: 'base64',
headers: [
{ key: 'X-Application-Developer', value: 'Amit Agarwal' },
{ key: 'X-Application-Version', value: 'v1.0.0.2' }
]
};
const messageId = await sendMail(options);
return messageId;
};
main()
.then((messageId) => console.log('Message sent successfully:', messageId))
.catch((err) => console.error(err));
إرسال رسائل البريد الإلكتروني الشخصية
إذا كنت ترغب في إرسال رسائل بريد إلكتروني مخصصة باستخدام Gmail وجداول بيانات Google، فيمكنك استخدام Mail Merge for Gmail.