简体   繁体   English

Python-发送带有附件的电子邮件

[英]Python--Sending a email with a attachment

I am working on a big project, that includes a database for remembering users. 我正在做一个大项目,其中包括一个用于记住用户的数据库。 il skip the details, but my client wants me to include a function by wich he can backup all the user data and other files. 我将跳过所有细节,但是我的客户希望我包括一个可以备份所有用户数据和其他文件的功能。

I was thinking of a email, (since the project is a android app) and I was trying to figure out how you could send a attachement (ie a .db sqlite3 file) in a email. 我在想一封电子邮件,(因为该项目是一个Android应用程序),并且我试图弄清楚如何在电子邮件中发送附件(即.db sqlite3文件)。 I know theres alot of similair questions around over here , but all of the answers to this question gives me a error. 我知道有很多的围了过来similair孤单的问题在这里 ,但所有的答案的这个问题给了我一个错误。 here is the closest that I got: 这是我最近得到的:

This program sends a email without a attachment: 该程序发送不带附件的电子邮件:

import smtplib

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

boodskap = MIMEText("Toekomsweb Epos toets", 'plain')

van_adres = "from adres"

na_adres = "to adres"

epos_liggaam = MIMEMultipart('alternatief')

epos_liggaam['Subject'] = "Toets"

epos_liggaam['From'] = van_adres

epos_liggaam['To'] = na_adres

epos_liggaam.attach(boodskap)

mail = smtplib.SMTP('smtp.gmail.com',587)

mail.ehlo()

mail.starttls()

mail.login(van_adres,'PASSWORD')

mail.sendmail(van_adres,na_adres,epos_liggaam.as_string())

mail.close()
print("succes!")

please excuse my poor variable naming, its not in english. 请原谅我可怜的变量命名,它不是英语。

any help on sending a attachment? 对发送附件有任何帮助吗?

Thanks! 谢谢!

Hi this is the code I used... it turns out that ubunto uses a different way of sending a email than windows. 嗨,这是我使用的代码...事实证明,ubunto使用不同于Windows的方式发送电子邮件。

import smtplib

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

from email.mime.base import MIMEBase

from email import encoders

import os

boodskap = MIMEText("Toekomsweb Epos toets", 'plain')

van_adres = 'From adres'

na_adres = 'To adres'

epos_liggaam = MIMEMultipart('alternatief')

epos_liggaam['Subject'] = "Toets"

epos_liggaam['From'] = van_adres

epos_liggaam['To'] = na_adres

epos_liggaam.attach(boodskap)

f = "toets.db"
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f)))
epos_liggaam.attach(part)

mail = smtplib.SMTP('smtp.gmail.com',587)

mail.ehlo()

mail.starttls()

mail.login(van_adres,'PASSWORD')

mail.sendmail(van_adres,na_adres,epos_liggaam.as_string())

mail.close()
print("succes!")

this answer was adapted from here (second answer) 此答案改编自此处 (第二个答案)

hope that this answer will answer other people's question aswell 希望这个答案也能回答其他人的问题

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

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