可以通过以下步骤完成:
gem install google-api-client
require 'google/apis/gmail_v1'
require 'googleauth'
require 'googleauth/stores/file_token_store'
定义用于身份验证的凭据文件路径和作用域
CREDENTIALS_PATH = 'path/to/credentials.json'
TOKEN_PATH = 'path/to/token.yaml'
SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_COMPOSE
创建一个新的Gmail API客户端
client = Google::Apis::GmailV1::GmailService.new
client.client_options.application_name = 'Your Application Name'
client.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open(CREDENTIALS_PATH),
scope: SCOPE
)
如果你之前已经进行过身份验证,可以加载现有的令牌
if File.exist?(TOKEN_PATH)
client.authorization = client.authorization.dup
client.authorization.token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)
end
构建电子邮件消息
message = Google::Apis::GmailV1::Message.new
message.raw = Base64.urlsafe_encode64(
<<~MESSAGE
From: sender@example.com
To: recipient@example.com
Subject: Attachment Test
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="boundary"
--boundary
Content-Type: text/plain; charset="UTF-8"
Please see the attached file.
--boundary
Content-Type: application/pdf
Content-Disposition: attachment; filename="example.pdf"
#{Base64.strict_encode64(File.read('path/to/example.pdf'))}
--boundary--
MESSAGE
)
client.send_user_message('me', message)
请确保将CREDENTIALS_PATH
和TOKEN_PATH
替换为你的凭据文件路径和令牌文件路径。还要将From
和To
字段替换为发送者和接收者的电子邮件地址。在Content-Type
头部中,你可以根据你要附加的文件类型进行相应的更改。
这是一个使用ruby中的google-api-client gem将文件附加到电子邮件的基本示例。你可以根据自己的需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云