Skip to content

电子邮件

¥Email

email 包允许从 Meteor 应用发送电子邮件。要使用它,请在终端中运行将包添加到你的项目中:

¥The email package allows sending email from a Meteor app. To use it, add the package to your project by running in your terminal:

bash
meteor add email

设置发送电子邮件的包有两种方法。

¥There are two ways on how to setup the package for sending e-mail.

首先是设置 MAIL_URL。服务器从 MAIL_URL 环境变量中读取以确定如何发送邮件。MAIL_URL 应该引用 SMTP 服务器并使用 smtp://USERNAME:PASSWORD@HOST:PORTsmtps://USERNAME:PASSWORD@HOST:PORT 形式。如果邮件服务器需要 TLS/SSL(并且不使用 STARTTLS),则应使用 smtps:// 表单(s 用于 "secure"),最常见于端口 465。在升级到 TLS/SSL(使用 STARTTLS)之前以未加密方式启动的连接通常使用端口 587(有时是 25),应该使用 smtp://。有关更多信息,请参阅 Nodemailer 文档

¥First is to set MAIL_URL. The server reads from the MAIL_URL environment variable to determine how to send mail. The MAIL_URL should reference an SMTP server and use the form smtp://USERNAME:PASSWORD@HOST:PORT or smtps://USERNAME:PASSWORD@HOST:PORT. The smtps:// form (the s is for "secure") should be used if the mail server requires TLS/SSL (and does not use STARTTLS) and is most common on port 465. Connections which start unencrypted prior to being upgraded to TLS/SSL (using STARTTLS) typically use port 587 (and sometimes 25) and should use smtp://. For more information see the Nodemailer docs

其次,如果你使用的是 支持的服务 之一,你可以在应用设置中设置发送选项,如下所示:

¥Second, if you are using a one of the supported services you can setup the sending options in your app settings like this:

json
{
  "packages": {
    "email": {
      "service": "Mailgun",
      "user": "postmaster@meteor.com",
      "password": "superDuperPassword"
    }
  }
}

包将处理其余部分。

¥The package will take care of the rest.

如果你使用受支持的服务,该包将尝试匹配受支持的服务并使用存储的设置。你可以通过将协议(如 smtp)切换到服务名称来强制执行此操作。不过你应该只将其用作权宜之计,而是正确设置设置。

¥If you use a supported service the package will try to match to supported service and use the stored settings instead. You can force this by switching protocol like smtp to the name of the service. Though you should only use this as a stop-gap measure and instead set the settings properly.

如果两个选项都未设置,Email.send 将改为将消息输出到标准输出。

¥If neither option is set, Email.send outputs the message to standard output instead.

仅从 Email v2.2 开始,包设置才可用

¥Package setting is only available since Email v2.2

Email.send

Server only

Summary:

Send an email with asyncronous method. Capture Throws an Error on failure to contact mail server or if mail server returns an error. All fields should match RFC5322 specification.

If the MAIL_URL environment variable is set, actually sends the email. Otherwise, prints the contents of the email to standard out.

Note that this package is based on nodemailer, so make sure to refer to the documentation when using the attachments or mailComposer options.

Arguments:

Source code
NameTypeDescriptionRequired
optionsObjectYes

Options:

NameTypeDescriptionRequired
fromString

"From:" address (required)

No
to, cc, bcc, replyToString

"To:", "Cc:", "Bcc:", and "Reply-To:" addresses

No
inReplyToString

Message-ID this message is replying to

No
referencesString

Array (or space-separated string) of Message-IDs to refer to

No
messageIdString

Message-ID for this message; otherwise, will be set to a random value

No
subjectString

"Subject:" line

No
text, htmlString

Mail body (in plain text and/or HTML)

No
watchHtmlString

Mail body in HTML specific for Apple Watch

No
icalEventString

iCalendar event attachment

No
headersObject

Dictionary of custom headers - e.g. { "header name": "header value" }. To set an object under a header name, use JSON.stringify - e.g. { "header name": JSON.stringify({ tracking: { level: 'full' } }) }.

No
attachmentsArray.<Object>

Array of attachment objects, as described in the nodemailer documentation.

No
mailComposerMailComposer

A MailComposer object representing the message to be sent. Overrides all other options. You can create a MailComposer object via new EmailInternals.NpmModules.mailcomposer.module.

No
encryptionKeysString

An array that holds the public keys used to encrypt.

No
shouldSignString

Enables you to allow or disallow email signing.

No

你必须提供 from 选项以及 toccbcc 中的至少一个;所有其他选项都是可选的。

¥You must provide the from option and at least one of to, cc, and bcc; all other options are optional.

Email.send 仅在服务器上工作。以下是客户端如何使用服务器方法调用发送电子邮件的示例。(在实际应用中,你需要小心限制客户端可以发送的电子邮件,以防止你的服务器被用作中继垃圾邮件发送者。)

¥Email.send only works on the server. Here is an example of how a client could use a server method call to send an email. (In an actual application, you'd need to be careful to limit the emails that a client could send, to prevent your server from being used as a relay by spammers.)

js
import { Meteor } from "meteor/meteor";
import { Email } from "meteor/email";
import { check } from "meteor/check";
// Server: Define a method that the client can call.
Meteor.methods({
  sendEmail({ to, from, subject, text }) {
    // Make sure that all arguments are strings.
    check([to, from, subject, text], [String]);

    Email.send({ to, from, subject, text });
  },
});
js
import { Meteor } from "meteor/meteor";
// Client: Asynchronously send an email.
Meteor.callAsync("sendEmail", {
  to: "Alice <alice@example.com>",
  from: "bob@example.com",
  subject: "Hello from Meteor!",
  text: "This is a test of Email.send.",
});

Email.sendAsync

Server only

Summary:

Send an email with asyncronous method. Capture Throws an Error on failure to contact mail server or if mail server returns an error. All fields should match RFC5322 specification.

If the MAIL_URL environment variable is set, actually sends the email. Otherwise, prints the contents of the email to standard out.

Note that this package is based on nodemailer, so make sure to refer to the documentation when using the attachments or mailComposer options.

Arguments:

Source code
NameTypeDescriptionRequired
optionsObjectYes

Options:

NameTypeDescriptionRequired
fromString

"From:" address (required)

No
to, cc, bcc, replyToString

"To:", "Cc:", "Bcc:", and "Reply-To:" addresses

No
inReplyToString

Message-ID this message is replying to

No
referencesString

Array (or space-separated string) of Message-IDs to refer to

No
messageIdString

Message-ID for this message; otherwise, will be set to a random value

No
subjectString

"Subject:" line

No
text, htmlString

Mail body (in plain text and/or HTML)

No
watchHtmlString

Mail body in HTML specific for Apple Watch

No
icalEventString

iCalendar event attachment

No
headersObject

Dictionary of custom headers - e.g. { "header name": "header value" }. To set an object under a header name, use JSON.stringify - e.g. { "header name": JSON.stringify({ tracking: { level: 'full' } }) }.

No
attachmentsArray.<Object>

Array of attachment objects, as described in the nodemailer documentation.

No
mailComposerMailComposer

A MailComposer object representing the message to be sent. Overrides all other options. You can create a MailComposer object via new EmailInternals.NpmModules.mailcomposer.module.

No

sendAsync 仅在服务器上工作。它的行为与 Email.send 相同,但返回一个 Promise。如果你定义了 Email.customTransport,则 callAsync 方法将返回 customTransport 方法的返回值或 Promise(如果此方法是异步的)。

¥sendAsync only works on the server. It has the same behavior as Email.send, but returns a Promise. If you defined Email.customTransport, the callAsync method returns the return value from the customTransport method or a Promise, if this method is async.

js
// Server: Define a method that the client can call.
Meteor.methods({
  sendEmail({ to, from, subject, text }) {
    // Make sure that all arguments are strings.
    check([to, from, subject, text], [String]);

    return Email.sendAsync({ to, from, subject, text }).catch((err) => {
      // do something with the error
    });
  },
});

Email.hookSend

Server only

Summary:

Hook that runs before email is sent.

Arguments:

Source code
NameTypeDescriptionRequired
ffunction

receives the arguments to Email.send and should return true to go ahead and send the email (or at least, try subsequent hooks), or false to skip sending.

Yes
js
import { Email } from 'meteor/email'

Email.hookSend(({to}) => {
  if (to === 'ceo@company.com') {
    console.log(`Let's not send email to the CEO`);
    return false;
  }
  return true;
})

如果你想要执行以下操作,hookSend 是一个方便的钩子:防止发送某些电子邮件,通过你自己的集成发送电子邮件,而不是 Meteor 提供的默认集成,或者对数据执行其他操作。如果你想拦截由核心软件包(如 accounts-password)或其他无法修改电子邮件代码的软件包发送的电子邮件,此功能特别有用。

¥hookSend is a convenient hook if you want to: prevent sending certain emails, send emails via your own integration instead of the default one provided by Meteor, or do something else with the data. This is especially useful if you want to intercept emails sent by core packages like accounts-password or other packages where you can't modify the email code.

钩子函数将接收一个带有 Nodemailer 选项的对象。

¥The hook function will receive an object with the options for Nodemailer.

Email.customTransport

Server only

Summary:

Overrides sending function with your own.

Arguments:

Source code
NameTypeDescriptionRequired
ffunction

function that will receive options from the send function and under packageSettings will include the package settings from Meteor.settings.packages.email for your custom transport to access.

Yes

Email.customTransport 仅从 Email v2.2 开始可用

¥Email.customTransport is only available since Email v2.2

在某些情况下,你会设置自己的传输,无论是邮件服务的 SDK 还是其他东西。这就是 customTransport 发挥作用的地方。如果你设置此功能,则所有发送事件都将传递给它(在 hookSend 运行之后),并将选项对象传递给 send 函数,并添加 packageSettings 键,该键将传入应用设置中设置的包设置(如果有)。在该函数中做什么取决于你,因为它将覆盖原始发送函数。

¥There are scenarios when you have your own transport set up, be it an SDK for your mailing service or something else. This is where customTransport comes in. If you set this function all sending events will be passed to it (after hookSend is run) with an object of the options passed into send function with addition of packageSettings key which will pass in package settings set in your app settings (if any). It is up to you what you do in that function as it will override the original sending function.

以下是使用 Mailgun 的简单示例:

¥Here is a simple example with Mailgun:

javascript
import { Email } from 'meteor/email'
import { Log } from 'meteor/logging'
import Mailgun from 'mailgun-js'

Email.customTransport = (data) => {
  // `options.packageSettings` are settings from `Meteor.settings.packages.email`
  // The rest of the options are from Email.send options
  const mailgun = Mailgun({ apiKey: data.packageSettings.mailgun.privateKey, domain: 'mg.mygreatapp.com' })

  // Since the data object that we receive already includes the correct key names for sending
  // we can just pass it to the mailgun sending message.
  mailgun.messages().send(data, (error, body) => {
    if (error) Log.error(error)
    if (body) Log.info(body)
  })
}

请注意,这还会覆盖控制台中消息的开发显示,因此你可能需要区分生产和开发以设置此功能。

¥Note that this also overrides the development display of messages in console so you might want to differentiate between production and development for setting this function.