【发布时间】:2017-08-15 14:30:23
【问题描述】:
从documentation,我看到可以在后端文件中定义主机、端口、用户名和密码,但我想在我的代码本身中定义所有这些。 这可以做到吗?如果有,怎么做?
from django.core.mail import EmailMessage
email = EmailMessage(
'Hello',
'Body goes here',
'from@example.com',
['to1@example.com', 'to2@example.com'],
['bcc@example.com'],
reply_to=['another@example.com'],
headers={'Message-ID': 'foo'},
)
message.attach_file('/images/weather_map.pdf')
提前致谢!
更新:
我想避免将凭据存储在任何文件中。最终,我希望代码提示输入用户名和密码作为输入变量。 更新:
我试过了:
import pandas as pd
from django.core.mail import EmailMessage
from django.core.mail.backends.smtp import EmailBackend
attachment_path=r'C:\path'+'\\'
connection = EmailBackend(
host='host',
port=587,
username='login',
password='password'
)
email = EmailMessage(
'Hello',
'Body goes here',
'example@example.com',
['example@example.com'],
['example@example.com'],
reply_to=['example@example.com'],
headers={'Message-ID': 'foo'},
connection=connection
)
email.attach_file(attachment_path+'attachment.pdf')
email.send()
【问题讨论】:
-
尽量避免在代码中存储凭据是一个很好的目标。但是,您应该考虑在设置中从环境变量加载凭据,而不是每次发送电子邮件时都传递凭据。
标签: python django email attachment