我正在使用Python 3而我正在尝试将文件附加到电子邮件中。我是MIME和SMTP的新手。 所以这是我的功能:
def func():
path = mypath
for file in glob.glob(path + "\\happy*"):
print(file)
sender = myemail
senderto = someonesemail
msg = MIMEMultipart('alternative')
msg['Subject'] = 'The File'
msg['From'] = sender
msg['To'] = senderto
body = "File"
msg.attach(MIMEText(body, 'plain'))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(file, encoding='charmap').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % file)
msg.attach(part)
global smtpSettings
smtpSettings = smtplib.SMTP(host=myhost, port=587)
print("Step 1 Complete")
smtpSettings.login(smtpusername, smtppassword)
print("Step 2 Complete")
smtpSettings.sendmail(sender, senderto, msg.as_string)
print("Step 3 Complete")
smtpSettings.quit()
print("Success")
旁注:senderto =接收者。 我得到的输出是:
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:/Users/Luis/Desktop/PYTHON/smtptestes.py", line 73, in func
smtpSettings.sendmail(sender, senderto, msg.as_string)
File "C:\Python34\lib\smtplib.py", line 769, in sendmail
esmtp_opts.append("size=%d" % len(msg))
TypeError: object of type 'method' has no len()
答案 0 :(得分:1)
在步骤3中修复,更改
smtpSettings.sendmail(sender, senderto, msg.as_string)
到
smtpSettings.sendmail(sender, senderto, msg.as_string())
因为as_string
是一种方法
答案 1 :(得分:0)
我是yagmail的维护者,这是一个使发送电子邮件(包含或不包含附件)更容易的软件包。
import yagmail
yag = yagmail.SMTP(myemail, 'mypassword')
yag.send(to = someonesemail, subject = 'The File', contents = ['File', file])
发送电子邮件只需要三行。尼斯!
内容会巧妙地猜测file
变量字符串指向一个文件,从而附加它。
完整代码可能是:
import yagmail
import glob
def func(path, user, pw, ):
subject = 'The File'
body = "File"
yag = yagmail.SMTP(user, pw, host = myhost)
for fname in glob.glob(path + "\\happy*"):
yag.send(someonesemail, subject, [body, fname])
func(mypath, smtpusername, smtppassword)