zoukankan      html  css  js  c++  java
  • python3.7发送邮件带附件

    代码:

     1 # -*- coding: utf-8 -*-
     2 
     3 import smtplib, ssl
     4 from email.mime.text import MIMEText
     5 from email.mime.multipart import MIMEMultipart
     6 
     7 
     8 def send_email_with_custom_smtp(sender_email, receiver_email, server, port, usr, password, subject, text, html,
     9                                 annex_path):
    10     # mail gun exception, switch to port 465
    11     # see: https://stackoverflow.com/questions/57715289/how-to-fix-ssl-sslerror-ssl-wrong-version-number-wrong-version-number-ssl
    12     if server == 'smtp.mailgun.org':
    13         port = 465
    14 
    15     message = MIMEMultipart("alternative")
    16     if annex_path is not None:
    17         for k in annex_path:
    18             attach = MIMEText(k['annexContent'], 'base64', 'utf-8')
    19             attach["Content-Type"] = 'application/octet-stream'
    20             attach.add_header('Content-Disposition', 'attachment', filename='{}'.format(k['annexName']))
    21             message.attach(attach)
    22     else:
    23         pass
    24     message["Subject"] = subject
    25     message["From"] = sender_email
    26     message["To"] = receiver_email
    27 
    28     # Turn these into plain/html MIMEText objects
    29     part1 = MIMEText(text, "plain")
    30     part2 = MIMEText(html, "html")
    31 
    32     # Add HTML/plain-text parts to MIMEMultipart message
    33     # The email client will try to render the last part first
    34     message.attach(part1)
    35     message.attach(part2)
    36 
    37 
    38     # Create a secure SSL context
    39     context = ssl.create_default_context()
    40     with smtplib.SMTP_SSL(server, port, context=context) as server:
    41         if int(port) == 587:
    42             server.starttls(context=context)
    43         try:
    44             server.login(usr, password)
    45         except:
    46             raise ValueError('登录失败,请检查邮箱用户名与密码(授权码)是否正确')
    47         try:
    48             server.sendmail(
    49                 sender_email, receiver_email, message.as_string()
    50             )
    51             return '邮件发送成功。', True
    52         except:
    53             return '邮件发送失败', False
  • 相关阅读:
    来电科技-自助租借充电宝
    一次使用NodeJS实现网页爬虫记
    八爪鱼采集器
    杭州市职称系统
    zz
    有道智选-网易效果推广
    Ubuntu10.04下载并编译Android4.3源代码
    poj 1654 Area 多边形面积
    Android利用Looper在子线程中改变UI
    Notepad 快捷键 大全
  • 原文地址:https://www.cnblogs.com/liqiongming/p/14593113.html
Copyright © 2011-2022 走看看