我认为这可能无关紧要,但对于那些有兴趣并遇到同样问题的人来说:
我正在使用适用于 Python 的 Google Gmail API。当我们处理 Google Apps 时,它更安全。虽然 SMTP 不是一个糟糕的选择,但我强烈推荐 Google API。
我正在使用 google API 示例(没有附件的示例),并且我意识到仅当主题或正文中的文本不是完整的字符串(即放入主题中的字符串)时才放置附件或者正文不是单个字符串而是字符串的集合。
为了更好地解释:
message = (service.users().messages().send(userId='me', body=body).execute())
body = ("Your OTP is", OTP)
这 (body = ("Your OTP is", OTP)) 可能适用于 print() 命令,但不适用于这种情况。您可以更改:
message = (service.users().messages().send(userId='me', body=body).execute())
body = ("Your OTP is", OTP)
到:
CompleteString = "Your OTP is " + OTP
message = (service.users().messages().send(userId='me', body=body).execute())
body = (CompleteString)
以上几行将正文的两个部分组成一个字符串。
另外:作为附件放置的“noname”文件仅包含写入的字符串。所以,如果你遵循这个:
message = (service.users().messages().send(userId='me', body=body).execute())
body = ("Your OTP is", OTP)
所以你在文件中得到的只是:“你的 OTP 是”
我还在这里添加了修改现有示例代码后得到的整个代码:https://developers.google.com/gmail/api/quickstart/python
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64
sender = "sender_mail"
print("Welcome to the Mail Service!")
reciever = input("Please enter whom you want to send the mail to - ")
subject = input("Please write your subject - ")
msg = input("Please enter the main body of your mail - ")
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
message = MIMEText(msg)
message['to'] = reciever
message['from'] = sender
message['subject'] = subject
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw' : raw}
message = (service.users().messages().send(userId='me', body=body).execute())
另请注意,此代码仅适用于通过邮件发送的文本。
附:我使用的是 Python 3.8,所以上面的代码可能不适用于 Python 2。