1. from openpyxl.writer.excel import save_virtual_workbook
    2. # ...
    3. response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.ms-excel')

    参考:https://exceptionshub.com/django-openpyxl-saving-workbook-as-attachment.html

    发送带附件的邮件

    1. # -*- coding:utf-8 -*-
    2. import urllib, urllib2
    3. import smtplib
    4. from email.mime.multipart import MIMEMultipart
    5. from email.mime.text import MIMEText
    6. from email.mime.application import MIMEApplication
    7. # 发件人地址,通过控制台创建的发件人地址
    8. username = 'xxx@xxx.com'
    9. # 发件人密码,通过控制台创建的发件人密码
    10. password = 'XXXXXXXX'
    11. # 收件人地址列表,支持多个收件人,最多30个
    12. rcptlist = ['to1@to.com', 'to2@to.com']
    13. receivers = ','.join(rcptlist)
    14. # 构建 multipart 的邮件消息
    15. msg = MIMEMultipart('mixed')
    16. msg['Subject'] = 'Test Email'
    17. msg['From'] = username
    18. msg['To'] = receivers
    19. # 构建 multipart/alternative 的 text/plain 部分
    20. alternative = MIMEMultipart('alternative')
    21. textplain = MIMEText('纯文本部分', _subtype='plain', _charset='UTF-8')
    22. alternative.attach(textplain)
    23. # 构建 multipart/alternative 的 text/html 部分
    24. texthtml = MIMEText('超文本部分', _subtype='html', _charset='UTF-8')
    25. alternative.attach(texthtml)
    26. # 将 alternative 加入 mixed 的内部
    27. msg.attach(alternative)
    28. # 附件类型
    29. # xlsx 类型的附件
    30. xlsxpart = MIMEApplication(open('测试文件1.xlsx', 'rb').read())
    31. xlsxpart.add_header('Content-Disposition', 'attachment', filename=Header("测试文件1.xlsx","utf-8").encode())
    32. msg.attach(xlsxpart)
    33. # jpg 类型的附件
    34. jpgpart = MIMEApplication(open('2.jpg', 'rb').read())
    35. jpgpart.add_header('Content-Disposition', 'attachment', filename=Header("2.jpg","utf-8").encode())
    36. msg.attach(jpgpart)
    37. # mp3 类型的附件
    38. mp3part = MIMEApplication(open('3.mp3', 'rb').read())
    39. mp3part.add_header('Content-Disposition', 'attachment', filename=Header("3.mp3","utf-8").encode())
    40. msg.attach(mp3part)
    41. # 发送邮件
    42. try:
    43. client = smtplib.SMTP()
    44. #python 2.7以上版本,若需要使用SSL,可以这样创建client
    45. #client = smtplib.SMTP_SSL()
    46. client.connect('smtpdm.aliyun.com')
    47. client.login(username, password)
    48. #发件人和认证地址必须一致
    49. client.sendmail(username, rcptlist, msg.as_string())
    50. client.quit()
    51. print '邮件发送成功!'
    52. except smtplib.SMTPRecipientsRefused:
    53. print '邮件发送失败,收件人被拒绝'
    54. except smtplib.SMTPAuthenticationError:
    55. print '邮件发送失败,认证错误'
    56. except smtplib.SMTPSenderRefused:
    57. print '邮件发送失败,发件人被拒绝'
    58. except smtplib.SMTPException,e:
    59. print '邮件发送失败, ', e.message

    参考:https://help.aliyun.com/knowledge_detail/51584.html?spm=a2c4g.11186623.6.579.71685c895XLIY7