【发布时间】:2017-07-10 08:54:58
【问题描述】:
我是 python 新手,我试图通过 Gmail 发送附加的电子邮件,而我提供的附件路径无法找到 Python。
class Email(object):
def __init__(self, from_, to, subject, message, message_type='plain',
attachments=None, cc=None, message_encoding='us-ascii'):
self.email = MIMEMultipart()
self.email['From'] = from_
self.email['To'] = to
self.email['Subject'] = subject
if cc is not None:
self.email['Cc'] = cc
text = MIMEText(message, message_type, message_encoding)
self.email.attach(text)
if attachments is not None:
mimetype, encoding = guess_type(attachments)
if mimetype ==None:
mimetype = "text/html"
mimetype = mimetype.split('/', 1)
with open(os.path.join(attachments, 'TestReport.html')) as f:
attachment = MIMEBase(mimetype[0], mimetype[1])
attachment.set_payload(f.read())
f.close()
encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(attachment))
self.email.attach(attachment)
下面的代码是我正在执行的文件,并使用 open(os.path.join(attachments, 'TestReport.html')) as f: 抛出错误:
IOError: [Errno 2] 没有这样的文件或目录:'C:/RelianceJio/wallet-fp-automation/email_utils\TestReport.html'
from email_utils.Email import EmailConnection, Email
config = ConfigParser.ConfigParser()
config.read(getcwd() + "/configuration.ini")
print 'I need some information...'
name = 'Lokesh Reddy'
email = 'lokeshreddyqa@gmail.com'
password = '***'
mail_server = 'smtp.gmail.com'
to_email = 'lokeshreddz@gmail.com'
to_name = 'Lokesh Reddy'
subject = 'Sending mail easily with Python'
message = 'here is the message body'
#os.chdir(getcwd() + "\ TestReport.html")
MYDIR = os.path.dirname(__file__)
attachments =MYDIR
print 'Connecting to server...'
server = EmailConnection(mail_server, email, password)
print 'Preparing the email...'
email = Email(from_='"%s" <%s>' % (name, email), # you can pass only email
to='"%s" <%s>' % (to_name, to_email), # you can pass only email
subject=subject, message=message, attachments=attachments)
print 'Sending...'
server.send(email)
print 'Disconnecting...'
server.close()
print 'Done!'
【问题讨论】:
-
No such file or directory: 'C:/RelianceJio/wallet-fp-automation/email_utils\TestReport.html'给你答案,你的文件在这个路径不存在 -
pyunit和python-unittest与此有何关系? -
文件存在同一路径
-
您应该检查问题是否与路径分隔符有关。你正在混合
/和`\`, -
混合 / 和 \ 可以,但在这种情况下应该不是问题,因为
\T不是有效的转义序列。另一个问题可能是 Python 中的路径区分大小写,而在 Windows 中则不区分大小写。该目录来自 Python 本身,所以应该没问题。我的猜测是文件名实际上是“testreport.html”或者可能是“TestReport.HTML”。
标签: python