我正在使用python开发一个应用程序,我需要通过邮件发送文件。我写了一个发送邮件的程序,但不知道有什么不对劲。代码发布在下面。请任何人帮我这个smtp库。我有什么遗失的吗?还有人可以告诉我什么是smtp的主机!我正在使用smtp.gmail.com。 任何人都可以告诉我如何通过电子邮件发送文件(.csv文件)。谢谢你的帮助!
#!/usr/bin/python
import smtplib
sender = 'someone@yahoo.com'
receivers = ['someone@yahoo.com']
message = """From: From Person <someone@yahoo.com>
To: To Person <someone@yahoo.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except:
print "Error: unable to send email"
答案 0 :(得分:3)
您没有登录。还有一些原因可能无法通过您的ISP进行阻止,如果无法向您发送反向DNS,则gmail会弹出您等等。
try:
smtpObj = smtplib.SMTP('smtp.gmail.com', 587) # or 465
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(account, password)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except:
print "Error: unable to send email"
我刚刚注意到您的请求可以附加文件。这改变了事情,因为现在你需要处理编码。虽然我不认为,但仍然没有那么难。
import os
import email
import email.encoders
import email.mime.text
import smtplib
# message/email details
my_email = 'myemail@gmail.com'
my_passw = 'asecret!'
recipients = ['jack@gmail.com', 'jill@gmail.com']
subject = 'This is an email'
message = 'This is the body of the email.'
file_name = 'C:\\temp\\test.txt'
# build the message
msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = my_email
msg['To'] = ', '.join(recipients)
msg['Date'] = email.Utils.formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(email.MIMEText.MIMEText(message))
# build the attachment
att = email.MIMEBase.MIMEBase('application', 'octet-stream')
att.set_payload(open(file_name, 'rb').read())
email.Encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
msg.attach(att)
# send the message
srv = smtplib.SMTP('smtp.gmail.com', 587)
srv.ehlo()
srv.starttls()
srv.login(my_email, my_passw)
srv.sendmail(my_email, recipients, msg.as_string())