当前位置:   article > 正文

使用python发送邮件

python发送邮件

在发送邮箱前 要开启自己的SMTP服务 QQ 邮箱一般默认关闭SMTP服务,得先去开启它。打开https://mail.qq.com/,登录你的邮箱。然后点击位于顶部的【设置】按钮,选择【账户设置】,然后下拉到这个位置。开启POP3/SMTP服务,验证后会给到一个授权码,后续服务端用该授权码登录邮箱。

之后就可以发邮箱啦:

文本邮件

  1. import smtplib
  2. # email 用于构建邮件内容
  3. from email.mime.text import MIMEText
  4. # 构建邮件头
  5. from email.header import Header
  6. # 发信方的信息:发信邮箱,QQ 邮箱授权码
  7. from_addr = '*******@qq.com' # 发生者的邮箱 您的qq邮箱
  8. password = '*******' # 刚才短信获取到的授权码
  9. # 收信方邮箱
  10. to_addr = '********@163.com'
  11. # 发信服务器
  12. smtp_server = 'smtp.qq.com'
  13. # 邮箱正文内容,第一个参数为内容,第二个参数为格式(plain 为纯文本),第三个参数为编码
  14. msg = MIMEText('使用python发送邮件测试', 'plain', 'utf-8')
  15. # 邮件头信息
  16. msg['From'] = Header('周**') # 发送者
  17. msg['To'] = Header('马大哈') # 接收者
  18. subject = 'Python SMTP 邮件测试' # 主题
  19. msg['Subject'] = Header(subject, 'utf-8') # 邮件主题
  20. smtpobj = smtplib.SMTP_SSL(smtp_server) # 创建对象
  21. try:
  22. # 建立连接--qq邮箱服务和端口号(可百度查询)
  23. smtpobj.connect(smtp_server, 465)
  24. # 登录--发送者账号和口令
  25. smtpobj.login(from_addr, password)
  26. # 发送邮件
  27. smtpobj.sendmail(from_addr, to_addr, msg.as_string())
  28. print("邮件发送成功")
  29. except smtplib.SMTPException:
  30. print("无法发送邮件")
  31. finally:
  32. # 关闭服务器
  33. smtpobj.quit()

如图:

附件邮件

  1. import smtplib
  2. # email 用于构建邮件内容
  3. from email.mime.text import MIMEText
  4. from email.mime.image import MIMEImage
  5. from email.mime.multipart import MIMEMultipart
  6. from email.mime.application import MIMEApplication
  7. # 构建邮件头
  8. from email.header import Header
  9. fromaddr = '*****@qq.com' # 发送者
  10. password = '*****corbafe' # 授权码
  11. toaddrs = ['*****16@163.com', '*****71@qq.com'] # 收件人
  12. content = '在干嘛呢. 亲'
  13. textApart = MIMEText(content)
  14. imageFile = 'img.png' # 图片文件
  15. imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
  16. imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)
  17. # pdfFile = '算法设计与分析基础第3版PDF.pdf'
  18. # pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
  19. # pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)
  20. # zipFile = '算法设计与分析基础第3版PDF.zip'
  21. # zipApart = MIMEApplication(open(zipFile, 'rb').read())
  22. # zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)
  23. m = MIMEMultipart()
  24. m.attach(textApart)
  25. m.attach(imageApart)
  26. # m.attach(pdfApart)
  27. # m.attach(zipApart)
  28. m['Subject'] = 'title'
  29. try:
  30. server = smtplib.SMTP('smtp.qq.com')
  31. server.login(fromaddr, password)
  32. server.sendmail(fromaddr, toaddrs, m.as_string())
  33. print('success')
  34. server.quit()
  35. except smtplib.SMTPException as e:
  36. print('error:', e) # 打印错误

如图:

html邮件 表格

  1. import smtplib
  2. # email 用于构建邮件内容
  3. from email.mime.text import MIMEText
  4. from email.mime.multipart import MIMEMultipart
  5. import datetime
  6. import pandas as pd
  7. yesterday = '2023' # 参数
  8. teacher_name = 'zhouxinxin' # 参数
  9. dept_name = '邮箱部' # 参数
  10. new_time = str(datetime.datetime.now().year) + '年' + str(datetime.datetime.now().month) + '月' + str(
  11. datetime.datetime.now().day) + '日'
  12. # pd.set_option('display.max_colwidth', -1)
  13. columns = ['一级分类', '二级分类', '三级分类', '科目分类', '科目名称', '预算金额(万元)', '备注', '课题编号']
  14. list = [[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]]
  15. filter_merge_data = pd.DataFrame(list, columns=columns)
  16. df_html = filter_merge_data.to_html(escape=False) # DataFrame数据转化为HTML表格形式
  17. head = \
  18. """
  19. <head>
  20. <meta charset="utf-8">
  21. <STYLE TYPE="text/css" MEDIA=screen>
  22. table.dataframe {
  23. border-collapse: collapse;
  24. border: 2px solid #a19da2;
  25. /*居中显示整个表格*/
  26. margin: auto;
  27. }
  28. table.dataframe thead {
  29. border: 2px solid #91c6e1;
  30. background: #f1f1f1;
  31. padding: 10px 10px 10px 10px;
  32. color: #333333;
  33. }
  34. table.dataframe tbody {
  35. border: 2px solid #91c6e1;
  36. padding: 10px 10px 10px 10px;
  37. }
  38. table.dataframe tr {
  39. }
  40. table.dataframe th {
  41. vertical-align: top;
  42. font-size: 14px;
  43. padding: 10px 10px 10px 10px;
  44. color: #105de3;
  45. font-family: arial;
  46. text-align: center;
  47. }
  48. table.dataframe td {
  49. text-align: center;
  50. padding: 10px 10px 10px 10px;
  51. }
  52. body {
  53. font-family: 宋体;
  54. }
  55. h1 {
  56. color: #5db446
  57. }
  58. div.header h2 {
  59. color: #0002e3;
  60. font-family: 黑体;
  61. }
  62. div.content h2 {
  63. text-align: center;
  64. font-size: 28px;
  65. text-shadow: 2px 2px 1px #de4040;
  66. color: #fff;
  67. font-weight: bold;
  68. background-color: #008eb7;
  69. line-height: 1.5;
  70. margin: 20px 0;
  71. box-shadow: 10px 10px 5px #888888;
  72. border-radius: 5px;
  73. }
  74. h3 {
  75. font-size: 22px;
  76. background-color: rgba(0, 2, 227, 0.71);
  77. text-shadow: 2px 2px 1px #de4040;
  78. color: rgba(239, 241, 234, 0.99);
  79. line-height: 1.5;
  80. }
  81. h4 {
  82. color: #e10092;
  83. font-family: 楷体;
  84. font-size: 20px;
  85. text-align: center;
  86. }
  87. td img {
  88. /*width: 60px;*/
  89. max-width: 300px;
  90. max-height: 300px;
  91. }
  92. </STYLE>
  93. </head>
  94. """
  95. body = \
  96. """
  97. <body>
  98. <div align="center" class="header">
  99. <!--标题部分的信息-->
  100. <h1 align="center">关于下达{yesterday}年各部门/专项经费预算指标的通知</h1>
  101. </div>
  102. <hr>
  103. <div class="content">
  104. <!--正文内容-->
  105. <h2> </h2>
  106. <div>
  107. <h4>{teacher_name}老师 您好:</h4>
  108. <h4>学校党委会已批准{yesterday}年各部门/专项预算方案,财务计划处已将预算指标导入ARP系统,请各位负责人及时查看,明细如下: </h4>
  109. {df_html}
  110. <h4>可登陆信息门户-预算管理系统查看预算详细信息,如有问题请联系财务计划处 联系电话:000012 任00 </h4>
  111. <h4>{dept_name}</h4>
  112. <h4>{new_time}</h4>
  113. </div>
  114. <hr>
  115. <p style="text-align: center">
  116. </p>
  117. </div>
  118. </body>
  119. """.format(yesterday=yesterday, teacher_name=teacher_name, new_time=new_time, dept_name=dept_name,
  120. df_html=df_html)
  121. html_msg = "<html>" + head + body + "</html>"
  122. html_msg = html_msg.replace('\n', '').encode("utf-8")
  123. _user = '1******5@qq.com'
  124. _pwd = 'wg******orbafe'
  125. _to = 'zj******16@163.com'
  126. msg = MIMEMultipart()
  127. msg["Subject"] = '预算下达邮件通知'
  128. msg["From"] = _user
  129. msg["To"] = _to
  130. part = MIMEText(html_msg, 'html', 'utf-8')
  131. msg.attach(part)
  132. s = smtplib.SMTP("smtp.qq.com", timeout=30)
  133. s.login(_user, _pwd)
  134. s.sendmail(_user, _to, msg.as_string())
  135. s.close()
  136. print('发送成功')

效果如下:

  1. '''
  2. 纯文本发送
  3. 构造邮件内容的MIMEText类有三个参数,第一个参数为文本内容,第二个参数‘plain’设置文本格式,第三个参数设置编码格式
  4. '''
  5. ## 导入模块
  6. import random
  7. from email.mime.multipart import MIMEMultipart
  8. from Models.models import *
  9. import smtplib
  10. # email 用于构建邮件内容
  11. from email.mime.text import MIMEText
  12. from email.mime.image import MIMEImage
  13. from email.mime.multipart import MIMEMultipart
  14. import pandas as pd
  15. from email.mime.application import MIMEApplication
  16. # 构建邮件头
  17. from email.header import Header
  18. from Settings.config import ServerIp
  19. # mail_host = "smtp.qq.com" #SMTP服务器地址
  20. # mail_sender = '1252****5@qq.com'
  21. # mail_passwd = 'wgxncm***corbafe'
  22. mail_list = [ # 发送列表
  23. {
  24. 'mail_host' : "smtp.qq.com", #SMTP服务器地址
  25. 'mail_sender' : '125287***5@qq.com',
  26. 'mail_passwd' : 'wgxncm***corbafe'
  27. },
  28. ]
  29. def get_mail_config(): # 获取一个发送账号
  30. b = random.choices(mail_list,k=1)[0]
  31. return b.get('mail_host'), b.get('mail_sender'), b.get('mail_passwd')
  32. def send_email_text(code=123, to=None): # 发送文本
  33. mail_host, mail_sender, mail_passwd = get_mail_config()
  34. ## 构造邮件内容
  35. content = f"您正在修改密码, 验证码为{code},验证码有效时长5分钟"
  36. msg = MIMEText(content, 'plain', 'utf-8')
  37. msg["Subject"] = "酒店管理密码修改"
  38. msg["From"] = mail_sender # 发送人
  39. msg["To"] = to # 接收人
  40. try:
  41. ## 发送邮件
  42. s = smtplib.SMTP() #实例化对象
  43. s.connect(mail_host, 25) #连接163邮箱服务器,端口号为25
  44. s.login(mail_sender, mail_passwd) #登录邮箱
  45. s.sendmail(mail_sender, [to], msg.as_string())
  46. s.quit()
  47. return {'code': '0', 'msg': '邮件发送成功!'}
  48. except Exception as e:
  49. return {'code': 500, 'msg': f'邮件发送失败, 方法为send_email_text2, 报错信息为{e}'}
  50. def send_email_text3(content=None,title=None, to=None, imageFile=None): # 专题图片邮件
  51. mail_host, mail_sender, mail_passwd = get_mail_config()
  52. head = \
  53. """
  54. <head>
  55. <meta charset="utf-8">
  56. </head>
  57. """
  58. body = \
  59. f"""
  60. <body>
  61. {content}
  62. <hr>
  63. <div class="content">
  64. <img src="{imageFile}"/>
  65. </div>
  66. </body>
  67. """
  68. html_msg = "<html>" + head + body + "</html>"
  69. html_msg = html_msg.replace('\n', '').encode("utf-8")
  70. msg = MIMEMultipart()
  71. msg["Subject"] = title
  72. msg["From"] = mail_sender
  73. msg["To"] = to
  74. try:
  75. part = MIMEText(html_msg, 'html', 'utf-8')
  76. msg.attach(part)
  77. s = smtplib.SMTP("smtp.qq.com", timeout=30)
  78. s.login(mail_sender, mail_passwd)
  79. s.sendmail(mail_sender, to, msg.as_string())
  80. s.close()
  81. print('发送成功')
  82. return {'code': '0', 'msg': '邮件发送成功!'}
  83. except smtplib.SMTPException as e:
  84. return {'code': 500, 'msg': f'邮件发送失败, 方法为send_email_text2, 报错信息为{e}'}
  85. def send_email_text4(
  86. content='',
  87. title='', to=None, datalist=None):
  88. mail_host, mail_sender, mail_passwd = get_mail_config()
  89. columns = ['客户名称', '公司名称', '职位', '客户类型', '会员等级']
  90. filter_merge_data = pd.DataFrame(datalist, columns=columns)
  91. df_html = filter_merge_data.to_html(escape=False) # DataFrame数据转化为HTML表格形式
  92. head = \
  93. """
  94. <head>
  95. <meta charset="utf-8">
  96. <STYLE TYPE="text/css" MEDIA=screen>
  97. table.dataframe {
  98. border-collapse: collapse;
  99. border: 2px solid #a19da2;
  100. /*居中显示整个表格*/
  101. margin: auto;
  102. }
  103. table.dataframe thead {
  104. border: 2px solid #91c6e1;
  105. background: #f1f1f1;
  106. padding: 10px 10px 10px 10px;
  107. color: #333333;
  108. }
  109. table.dataframe tbody {
  110. border: 2px solid #91c6e1;
  111. padding: 10px 10px 10px 10px;
  112. }
  113. table.dataframe tr {
  114. }
  115. table.dataframe th {
  116. vertical-align: top;
  117. font-size: 14px;
  118. padding: 10px 10px 10px 10px;
  119. color: #105de3;
  120. font-family: arial;
  121. text-align: center;
  122. }
  123. table.dataframe td {
  124. text-align: center;
  125. padding: 10px 10px 10px 10px;
  126. }
  127. body {
  128. font-family: 宋体;
  129. }
  130. h1 {
  131. color: #5db446
  132. }
  133. div.header h2 {
  134. color: #0002e3;
  135. font-family: 黑体;
  136. }
  137. div.content h2 {
  138. text-align: center;
  139. font-size: 28px;
  140. text-shadow: 2px 2px 1px #de4040;
  141. color: #fff;
  142. font-weight: bold;
  143. background-color: #008eb7;
  144. line-height: 1.5;
  145. margin: 20px 0;
  146. box-shadow: 10px 10px 5px #888888;
  147. border-radius: 5px;
  148. }
  149. h3 {
  150. font-size: 22px;
  151. background-color: rgba(0, 2, 227, 0.71);
  152. text-shadow: 2px 2px 1px #de4040;
  153. color: rgba(239, 241, 234, 0.99);
  154. line-height: 1.5;
  155. }
  156. h4 {
  157. color: #e10092;
  158. font-family: 楷体;
  159. font-size: 20px;
  160. text-align: center;
  161. }
  162. td img {
  163. /*width: 60px;*/
  164. max-width: 300px;
  165. max-height: 300px;
  166. }
  167. </STYLE>
  168. </head>
  169. """
  170. body = \
  171. f"""
  172. <body>
  173. <div class="content">
  174. <div>
  175. {content}:
  176. {df_html}
  177. </div>
  178. <hr>
  179. <p style="text-align: center">
  180. </p>
  181. </div>
  182. </body>
  183. """
  184. html_msg = "<html>" + head + body + "</html>"
  185. html_msg = html_msg.replace('\n', '').encode("utf-8")
  186. msg = MIMEMultipart()
  187. msg["Subject"] = title
  188. msg["From"] = mail_sender
  189. msg["To"] = to
  190. part = MIMEText(html_msg, 'html', 'utf-8')
  191. msg.attach(part)
  192. s = smtplib.SMTP("smtp.qq.com", timeout=30)
  193. s.login(mail_sender, mail_passwd)
  194. s.sendmail(mail_sender, to, msg.as_string())
  195. s.close()
  196. print('发送成功')
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/701862
推荐阅读
相关标签
  

闽ICP备14008679号