一、网上转载代码
import smtplib
from email.mime.text import MIMEText
#设置服务器所需信息
#163邮箱服务器地址
mail_host = 'smtp.163.com'
#163用户名
mail_user = '159*****02'
#密码(部分邮箱为授权码)
mail_pass = '7******x'
#邮件发送方邮箱地址
sender = '159*****02@163.com'
#邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receivers = ['59*****02@qq.com']
#设置email信息
#邮件内容设置
message = MIMEText('content','plain','utf-8')
#邮件主题
message['Subject'] = 'title'
#发送方信息
message['From'] = sender
#接受方信息
message['To'] = receivers[0]
#登录并发送邮件
try:
smtpObj = smtplib.SMTP()
#连接到服务器
smtpObj.connect(mail_host,25)
#登录到服务器
smtpObj.login(mail_user,mail_pass)
#发送
smtpObj.sendmail(
sender,receivers,message.as_string())
#退出
smtpObj.quit()
print('success')
except smtplib.SMTPException as e:
print('error',e) #打印错误
二、我写的用在项目中的代码如下,加入了可选参数和抄送Cc:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
# 设置服务器所需信息
# 第三方 SMTP 服务服务器地址
mail_host = 'mail.abc.com'
# 用户名
mail_user = 'Tony'
# 密码(部分邮箱为授权码)
mail_pass = '123123123'
# 邮件发送方邮箱地址
sender = 'Tony@abc.com'
# 邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
to_receivers = ["Dandy@abc.com", "Tom@abc.com"]
# 抄送(没有抄送可以去掉)
cc_receivers = ["Jack@abc.com", "David@abc.com"]
default_encoding = 'utf-8'
# 默认邮件主题文字
subject = '【Dashboard】 Cronjob Run ERROR'
def handler(_content, _subject=subject, _to_receivers=to_receivers, _cc_receivers=cc_receivers):
mail(_content, _subject, _to_receivers, _cc_receivers)
def mail(_content, _subject, _to_receivers, _cc_receivers):
# # 设置email内容
message = MIMEText(_content, 'plain', default_encoding)
# # 设置email头信息(不设置的话也能发送,但是接收方的“头信息”格式显示会有问题)
# 邮件主题
message['Subject'] = _subject
# 发送方信息
message['From'] = sender
# 接受方信息
message['To'] = ','.join(_to_receivers)
# 抄送(没有抄送可以去掉)
message['Cc'] = ','.join(_cc_receivers)
# 登录并发送邮件
try:
smtp_obj = smtplib.SMTP()
# 连接到服务器 # 25 为 SMTP 端口号
smtp_obj.connect(mail_host, 25)
# 登录到服务器
smtp_obj.login(mail_user, mail_pass)
# 发送
smtp_obj.sendmail(sender, _to_receivers + _cc_receivers, message.as_string())
# 退出
smtp_obj.quit()
print('success:', '邮件发送成功.')
except smtplib.SMTPException as e:
print('error: ', '邮件发送失败.', e)
if __name__ == '__main__':
handler("test~")
部分参考自: