以下Python函数导致附件被命名为“noname”,它应该是“text_file.txt”。正如您所看到的,我尝试了两种不同的MIMEBase和MIMEApplication方法。我也试过MIMEMultipart('替代')无济于事。
def send_email(from_addr, to_addr_list,
subject, html_body,plain_text_body,
login,
password,
smtpserver='smtp.gmail.com:587',
cc_addr_list=None,
attachment=None,
from_name=None):
message=MIMEMultipart()
plain=MIMEText(plain_text_body,'plain')
html=MIMEText(html_body,'html')
message.add_header('from',from_name)
message.add_header('to',','.join(to_addr_list))
message.add_header('subject',subject)
if attachment!=None:
#attach_file=MIMEBase('application',"octet-stream")
#attach_file.set_payload(open(attachment,"rb").read())
#Encoders.encode_base64(attach_file)
#f.close()
attach_file=MIMEApplication(open(attachment,"rb").read())
message.add_header('Content-Disposition','attachment; filename="%s"' % attachment)
message.attach(attach_file)
message.attach(plain)
message.attach(html)
server = smtplib.SMTP(smtpserver)
server.starttls()
server.login(login,password)
server.sendmail(from_addr, to_addr_list, message.as_string())
server.quit()
我如何调用该函数:
send_email(
from_addr=from_email,
to_addr_list=["some_address@gmail.com"],
subject=subject,
html_body=html,
plain_text_body=plain,
login=login,
password=password,
from_name=display_name,
attachment="text_file.txt"
)
答案 0 :(得分:6)
您的标头不正确。 filename
是属性而不是字符串。
# Add header to variable with attachment file
attach_file.add_header('Content-Disposition', 'attachment', filename=attachment)
# Then attach to message attachment file
message.attach(attach_file)
答案 1 :(得分:0)
我认为这可能无关紧要,但对于那些感兴趣并遇到相同问题的人来说:
我也使用了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())
请注意,此代码仅适用于通过邮件放置的 text 。
P.S。我正在使用Python 3.8,因此上述代码可能不适用于Python 2。