Django电子邮件-定义用户名和密码

Dan*_*ty2 0 python email django attachment

文档中,我可以在后端文件中定义主机,端口,用户名和密码,但是我想在代码本身中定义所有它们。能做到吗?如果是这样,怎么办?

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')
Run Code Online (Sandbox Code Playgroud)

提前致谢!

更新:

我想避免将凭证存储在任何文件中。最终,我希望代码提示输入用户名和密码作为输入变量。 更新:

我尝试了这个:

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()
Run Code Online (Sandbox Code Playgroud)

Ala*_*air 5

您可以get_connection用来实例化电子邮件后端:

from django.core.mail import get_connection

connection = get_connection(
    host='...',
    port='...',
    username='...',
    ...
)
Run Code Online (Sandbox Code Playgroud)

然后在实例化时传递您的连接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'},
    connection=connection,
)
Run Code Online (Sandbox Code Playgroud)