python 发邮件 本地smtp_使用 Python 通过 SMTP 发送邮件的代码

分享一下使用 Python 通过 SMTP 发送邮件的方法,废话不多说,直接分享代码。主要使用到了 smtplib 和 email 这两个库,代码里重要部分已经加了注释,相信大家都能看懂。

一、使用 Python 通过 SMTP 发送邮件的代码# -*- coding:utf-8 -*-

import smtplib

import email

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

from email.mime.image import MIMEImage

from email.mime.base import MIMEBase

from email.mime.application import MIMEApplication

from email.header import Header

# 发件人地址,通过控制台创建的发件人地址

username = '***'

# 发件人密码,通过控制台创建的发件人密码

password = '***'

# 自定义的回复地址

replyto = '***'

# 收件人地址或是地址列表,支持多个收件人,最多30个

#rcptto = ['***', '***']

rcptto = '***'

# 构建alternative结构

msg = MIMEMultipart('alternative')

msg['Subject'] = Header('自定义信件主题'.decode('utf-8')).encode()

msg['From'] = '%s ' % (Header('自定义发信昵称'.decode('utf-8')).encode(), username)

msg['To'] = rcptto

msg['Reply-to'] = replyto

msg['Message-id'] = email.utils.make_msgid()

msg['Date'] = email.utils.formatdate()

# 构建alternative的text/plain部分

textplain = MIMEText('自定义TEXT纯文本部分', _subtype='plain', _charset='UTF-8')

msg.attach(textplain)

# 构建alternative的text/html部分

texthtml = MIMEText('自定义HTML超文本部分', _subtype='html', _charset='UTF-8')

msg.attach(texthtml)

# 发送邮件

try:

client = smtplib.SMTP()

#python 2.7以上版本,若需要使用SSL,可以这样创建client

#client = smtplib.SMTP_SSL()

#SMTP普通端口为25或80

client.connect('smtpdm.aliyun.com', 25)

#开启DEBUG模式

client.set_debuglevel(0)

client.login(username, password)

#发件人和认证地址必须一致

#备注:若想取到DATA命令返回值,可参考smtplib的sendmaili封装方法:

# 使用SMTP.mail/SMTP.rcpt/SMTP.data方法

client.sendmail(username, rcptto, msg.as_string())

client.quit()

print '邮件发送成功!'

except smtplib.SMTPConnectError, e:

print '邮件发送失败,连接失败:', e.smtp_code, e.smtp_error

except smtplib.SMTPAuthenticationError, e:

print '邮件发送失败,认证错误:', e.smtp_code, e.smtp_error

except smtplib.SMTPSenderRefused, e:

print '邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error

except smtplib.SMTPRecipientsRefused, e:

print '邮件发送失败,收件人被拒绝:', e.smtp_code, e.smtp_error

except smtplib.SMTPDataError, e:

print '邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error

except smtplib.SMTPException, e:

print '邮件发送失败, ', e.message

except Exception, e:

print '邮件发送异常, ', str(e)

二、参考文献和其他

多说几句,目前很多 VPS 已经封禁了 25 端口,所以如果想要使用 VPS 发送邮件,尽量使用 80 端口或者 465 端口(SSL 加密)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值