【问题标题】:How to add attachments to an Email with python code? [duplicate]如何使用 python 代码将附件添加到电子邮件中? [复制]
【发布时间】:2014-07-18 14:37:15
【问题描述】:
这是我的代码,它可以工作,但我想将 .txt 文件连同它一起发送超过 4 个。
我该怎么做呢?谢谢!
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.login("Email@gamil.com", "password")
msg = "\n"
server.sendmail("From", "To", msg)
【问题讨论】:
标签:
python
file
email
text
【解决方案1】:
我用它来使用 gmail 发送带有附件的邮件:
def send_mail(send_from, send_to, files=[]):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime=True)
if len(string_files)==1:
msg['Subject'] = 'Sending file: %s' % files[0]
else:
msg['Subject'] = 'Sending file: %s and others' % files[0]
text='This message has followng attachments'
for filename in string_files:
text+='\n%s' % filename
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com:587')
smtp.starttls()
# if you store password in a keyring (like gnome-keyring)
import keyring
gmail_password = keyring.get_password('gmail', 'personal')
# or just gmail_password='password'
smtp.login('yourgmailaddress', gmail_password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()