简体   繁体   English

如何使用 email 模块通过 Python email 发送文件?

[英]How do I send files in an email by using the Python email module?

I heared, that you can send files per email using the email module.我听说,您可以使用 email 模块发送每个 email 的文件。 How do I do that?我怎么做?

Take a look at: Here 看看: 这里

example from the site 该站点的示例

# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'

# Assume we know that the image files are all in PNG format
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class 
    automatically
    # guess the specific image type.
    fp = open(file, 'rb')
    img = MIMEImage(fp.read())
    fp.close()
    msg.attach(img)

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()

Given that you've already created a multipart: 鉴于您已经创建了一个多部分:

msg = MIMEMultipart()

Then you can add an image by doing: 然后,您可以通过执行以下操作添加图像:

filename = "..."
with open(filename, "rb") as f:
    attachment = MIMEImage(f.read())

or you can add the string "Hello World" as a test.txt by doing: 或者您可以通过执行以下操作将字符串"Hello World"添加为test.txt

filename = "test.txt"
attachment = MIMEText("Hello World")

For binary files or just in general, you can do: 对于二进制文件或只是一般而言,您可以执行以下操作:

filename = "..."
ctype, encoding = mimetypes.guess_type(filename)
maintype, subtype = ctype.split("/", 1)
attachment = MIMEBase(maintype, subtype)
with open(filename, "rb") as f:
    attachment.set_payload(f.read())
encoders.encode_base64(attachment)

Remember from email import encoders . 记住from email import encoders

At the end you add them to the email by doing: 最后,您可以通过以下操作将它们添加到电子邮件中:

attachment.add_header("Content-Disposition", "attachment", filename=filename)
msg.attach(attachment)

One important thing to remember, is that all files must be added first. 要记住的重要一件事是必须首先添加所有文件。 The message must come last in order to conform with RFC 2046 , which dictates: 为了符合RFC 2046 ,该消息必须排在最后,该RFC 2046规定:

Receiving user agents should pick and display the last format they are capable of displaying. 接收用户代理应选择并显示他们能够显示的最后一种格式。

You should first know the basics and focus on learning to send a basic email. first, we have built-in module in python 'email' so we use its class 'EmailMessage'您应该首先了解基础知识并专注于学习发送基本的 email。首先,我们在 python 'email' 中内置了模块,因此我们使用其 class 'EmailMessage'

from email.message import EmailMessage

Let's assume you would be using gmail. To send mail you should first enable 'less secure apps' in mail settings, this step is required to be able to send emails from a python script or you get a connection denied error while trying to send email. next, you should import libraries for sending message through SMTP假设您将使用 gmail。要发送邮件,您应该首先在邮件设置中启用“不太安全的应用程序”,需要执行此步骤才能从 python 脚本发送电子邮件,否则在尝试发送 email 时出现连接被拒绝错误.接下来,你应该导入通过SMTP发送消息的库

import smtplib, ssl

email only sends strings through smtp and thus for sending any attachment you must convert it to strings using mimetypes email 仅通过 smtp 发送字符串,因此要发送任何附件,您必须使用 mimetypes 将其转换为字符串

import mimetypes

also you require os module for processing attachment您还需要 os 模块来处理附件

import os

To enter password of email service at time of running script and in hidden way use getpass module要在运行脚本时以隐藏方式输入 email 服务的密码,请使用 getpass 模块

import getpass

now, we can create an object for message现在,我们可以为消息创建一个 object

message=EmailMessage()

now you should keep in mind, email object is like a dictionary, so go accordingly现在你应该记住,email object 就像一本字典,所以 go 相应地

message['From']='sender address as string'
message['To']='recipient address as string'
message['Subject']='subject of email as string'

body is little different, if you have one line body it can be just a string otherwise for nice formatting use docstring body 有点不同,如果你有一行 body 它可以只是一个字符串,否则为了漂亮的格式化使用 docstring

body="""Hello!
        World"""
message.set_content(body)

now let's prepare attachment, first we process its path现在让我们准备附件,首先我们处理它的路径

attachment_path='use absolute path if possible for better implementation'
attachment_filename=os.path.basename(attachment_path)

If MIME type and subtype is not known mimetypes module can be used as:如果 MIME 类型和子类型未知,mimetypes 模块可以用作:

mime_type, _ = mimetypes.guess_type(attachment_path)

Since we get 'mime_type' as type of mime and subtype separated by '/' we separate them as:由于我们将“mime_type”作为由“/”分隔的 mime 类型和子类型,因此我们将它们分隔为:

mime_type, mime_subtype=mime_type.split('/', 1)

now we are ready to convert the attachment to a string and attach to the 'message' object现在我们准备好将附件转换为字符串并附加到“消息”object

with open(attachment_path, 'rb') as ap:
message.add_attachment(ap.read(), maintype=mime_type, subtype=mime_subtype, filename=attachment_filename)

let's get to sending email:让我们开始发送 email:

with smtplib.SMTP("smtp.gmail.com", port=587) as smtp:
  #smtp.set_debuglevel(1) #uncomment this statement to get processing information(run in debug mode)
  smtp.starttls()
  mail_pass=getpass.getpass('Password? ') #uncomment this statement to enter password at time of execution of script
  #default prompt is 'password' for getpass method
  smtp.login(message['From'], mail_pass) #NOTE:here password is in plain context
  #To use password in more secure way, use getpass module
  smtp.send_message(message)

To know if your message sent successfully, let's add要知道您的消息是否发送成功,让我们添加

print('message sent successfully from {} to {}'.format(message['From'], message['To']))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM