Python smtplib发送的附件文件名中的Noname

时间:2019-06-08 04:24:21

标签: python smtp smtplib

我可以使用smtplib发送邮件。但是当我附加一个文件时,显示的名称是“ noname”。我正在使用以下代码:

attach_file_name = 'archivo.txt'

attach_file = open(attach_file_name, 'rb') 
payload = MIMEBase('application', 'octate-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload) 

payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)

代码是从此source

中获取的

1 个答案:

答案 0 :(得分:0)

我认为这可能无关紧要,但对于那些感兴趣并遇到相同问题的人来说:

我正在使用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())

请注意,此代码仅适用于通过邮件放置的文本。

P.S。我正在使用Python 3.8,因此上述代码可能不适用于Python 2。

相关问题