电子邮件错误帮助我解决语法错误

时间:2014-02-05 18:04:28

标签: python email smtplib

import smtplib  
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg.attach(MIMEText(file("P:/Email/test.txt").read()))



sender = 'sender@email.com'  
reciever  = 'reciever@email.com'  
msg = 'Hello'  


# Credentials (if needed)  
username = 'user'  
password = 'pass'  

# The actual mail send  
server = smtplib.SMTP('localhost')  
server.starttls()  
server.login(username,password)  
server.sendmail(sender, reciever, msg)  
server.quit()  

回溯(最近一次呼叫最后):文件“attach2.py”,第27行,在中 server.sendmail(sender,reciever,msg)文件“C:\ Python33 \ lib \ smtplib.py”,第775行,in sendmail(code,resp)= self.data(msg)文件“C:\ Python33 \ lib \ smtplib.py”,第516行,in data q = _quote_periods(msg)文件“C:\ Python33 \ lib \ smtplib.py”,第167行,in quote_periods返回re.sub(br'(?m)^。',b'..',bindata)文件“C:\ Python33 \ lib \ re.py”, 第170行,在子返回_compile(pattern,flags).sub(repl,string,count)TypeError: 预期的字符串或缓冲区

为什么我看到此错误消息。我的python库文件有问题吗?

2 个答案:

答案 0 :(得分:2)

前一行缺少右括号。

...
msg = MIMEMultipart()
msg.attach(MIMEText(file("P:/Email/test.txt").read())) # line missing a parenthesis

sender = 'whosends@something.com'
...

答案 1 :(得分:0)

您的代码有2个错误。这是我的纠正

import smtplib  
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg.attach(MIMEText(file("P:/Email/test.txt").read()))



sender = 'sender@email.com'  
reciever  = 'reciever@email.com'  

# ***here don't overwrite the MIMEMultipart() obj***
# msg = 'Hello'  


# Credentials (if needed)  
username = 'user'  
password = 'pass'  

# The actual mail send  
server = smtplib.SMTP('localhost')  
server.starttls()  
server.login(username,password)

# ***here msg.as_string() to convert the MIMEMultipart() obj to a string***
server.sendmail(sender, reciever, msg.as_string())  

server.quit()