python通过代理服务器发送邮件

最近公司的项目需要将测试报告以邮件形式发送出去,邮件为html格式。不过在公司内网无法通过一般的代理服务器发送邮件的,只能通过socks网关来访问外网的email服务器(我使用的同事已经搭好的socks5代理服务器)。

网上查找的主要方式都是使用PySocks来设置代理的:

import socks
import socket
socks.set_default_proxy(socks.HTTP, '地址', 端口, True, 用户名, 密码)
socket.socket = socks.socksocket

使用类似的方法设置了好几次还是不行,最后查到了一个chilkat库,官网上有比较详细的介绍:
https://www.example-code.com/python/smtp_socks_proxy.asp

发邮件模块

import sys
import chilkat
import time


def send_mail():
    mailman = chilkat.CkMailMan()
    mht = chilkat.CkMht()
    email = chilkat.CkEmail()

    #  Any string argument automatically begins the 30-day trial.
    success = mailman.UnlockComponent("Anything for 30-day trial")
    if not success:
        print(mailman.lastErrorText())
        sys.exit()

    success = mht.UnlockComponent("Anything for 30-day trial")
    if not success:
        print(mht.lastErrorText())
        sys.exit()

    mht.put_UseCids(True)
    # 本地文件路径
    report_path = sys.path[0] + "\\report.html"
    eml_str = mht.getEML(report_path)
    if not mht.get_LastMethodSuccess():
        print(mht.lastErrorText())
        sys.exit()

    success = email.SetFromMimeText(eml_str)
    if not success:
        print(email.lastErrorText())
        sys.exit()

    now = time.strftime("%Y-%m-%d-%H:%M:%S")
    email.put_Subject(邮件标题 + now)
    email.AddTo(收件人称呼, 收件人)

	# 下面是我的socks5代理服务器配置
    mailman.put_SocksHostname("192.168.1.10")
    mailman.put_SocksPort(6666)
    mailman.put_SocksVersion(5)
    mailman.put_SmtpHost("smtp.exmail.qq.com")
    mailman.put_SmtpUsername(邮箱账号)
    mailman.put_SmtpPassword(密码)
    # 不指定端口也能运行
    # mailman.put_SmtpPort(25)
    email.put_From(发件人)

    success = mailman.SendEmail(email)
    if not success:
        print(mailman.lastErrorText())
        sys.exit()

    success = mailman.CloseSmtpConnection()
    if not success:
        print(mailman.lastErrorText())
        sys.exit()

    print("HTML Email Sent!")


if __name__ == "__main__":
    send_mail()

猜你喜欢

转载自blog.csdn.net/Senmier/article/details/86654879