我的数据库中有文件url。我想将文件作为附件发送到电子邮件中。我已经尝试了以下代码
def mail_business_plan(sender, instance, created, **kwargs):
if created:
ctx = {"ctx":instance}
from_email = 'info@some_email.in'
subject = 'Business Plan by' + instance.company_name
message = get_template('email/business_team.html').render(ctx)
to = ['some_email@gmail.com']
mail = EmailMessage(subject, message, to=to, from_email=from_email)
mail.attach_file(instance.presentation, instance.presentation.read(), instance.presentation.content_type)
return mail.send()
我收到“ AttributeError:'FieldFile'对象没有属性'content_type'”的错误
如果文件路径存储在数据库中,发送带有附件的邮件的最佳方法是什么。
答案 0 :(得分:2)
假设您有一个模型,
class MyModel(models.Model):
# other fields
presentation = models.FileField(upload_to='some/place/')
并在您的信号
import mimetypes
def mail_business_plan(sender, instance, created, **kwargs):
if created:
ctx = {"ctx": instance}
from_email = 'info@some_email.in'
subject = 'Business Plan by' + instance.company_name
message = get_template('email/business_team.html').render(ctx)
to = ['some_email@gmail.com']
mail = EmailMessage(subject, message, to=to, from_email=from_email)
content_type = mimetypes.guess_type(instance.presentation.name)[0] # change is here <<<
mail.attach_file(instance.presentation, instance.presentation.read(), content_type) # <<< change is here also
return mail.send()
答案 1 :(得分:0)
在python中发送电子邮件的最佳方法是使用smtp
以下是在ubuntu中配置后缀和发送邮件的步骤。
sudo apt-get install mailutils
对于所有弹出式窗口只需按OK(您可以稍后更改主机名)
sudo vim /etc/postfix/main.cf
将以下行from inet_interfaces = all
更改为inet_interfaces = localhost
sudo service postfix restart
完成所有这些步骤后,尝试以下代码
import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def send_email(subject, message, from_email, to_email=[], attachment=[]):
"""
:param subject: email subject
:param message: Body content of the email (string), can be HTML/CSS or plain text
:param from_email: Email address from where the email is sent
:param to_email: List of email recipients, example: ["a@a.com", "b@b.com"]
:param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
"""
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ", ".join(to_email)
msg.attach(MIMEText(message, 'html'))
for f in attachment:
with open(f, 'rb') as a_file:
basename = os.path.basename(f)
part = MIMEApplication(a_file.read(), Name=basename)
part[
'Content-Disposition'] = 'attachment; filename="%s"' % basename
msg.attach(part)
email = smtplib.SMTP('localhost')
email.sendmail(from_email, to_email, msg.as_string())
答案 2 :(得分:0)
我通过更改
获得了解决方案mail.attach_file(instance.presentation, instance.presentation.read(), instance.presentation.content_type)
到
mail.attach_file(instance.presentation.path)