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
  • 相关阅读:
    转:C#操作摄像头
    C# Memcached缓存
    WCF:调用方未由服务器进行身份验证
    SQL Server 存储过程进行分页查询
    SQL Server T-SQL高级查询
    C#设计模式总结(转)
    C#中构造函数和析构函数区别
    C#: static关键字的作用(转)
    C#结构体和类的区别(转)
    .NET多线程编程(转)
  • 原文地址:https://www.cnblogs.com/liqiongming/p/14593113.html
Copyright © 2011-2022 走看看