Python SMTP发送邮件 python2,python3通用
业务需求:集群每天会生成一些统计的excell报表,需要将这些excell报表定时发送到相关邮箱。主要分为三步
- ** 实例化邮件传输实例,和邮件服务器建立连接(打开邮箱)
smtpObj = smtplib.SMTP()
smtpObj.connect('smtp.163.com',25)
# 需要SSL认证
# smtpObj = smtplib.SMTP_SSL(self.yaml_info['email_info']['email_host'])
smtpObj.login('yangjuncsdn@163.com','passwd是授权码,不是邮箱密码')
print()
- ** 书写邮件正文和附件等信息(写邮件)
#推荐使用html格式的正文内容,这样比较灵活,可以附加图片地址,调整格式等
with open("{}/../conf/{}".format(self.current_pwd, 'freemud.html'), 'r') as f:
content = f.read()
# # 设置html格式参数
part1 = MIMEText(content, 'html', 'utf-8')
message.attach(part1)
- ** 发送邮件
smtpObj.sendmail('yangjuncsdn@163.com', ['10127369556@qq.com'], message.as_string())
完整代码
在代码的上一级目录,还有conf和utilstool文件夹,里面分别有freemud.html,freemud.yaml;utilstools.py文件;
# coupon_reporting_email.py
# -*-coding=utf-8-*-
import email
import mimetypes
import sys
import os
import smtplib
try:
# python 2
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.utils import formatdate
except ImportError:
# python 3
from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
# sys.path.append("/home/etl_user/etl/dependencies/python-2.7.5/d_site_packages/site-packages")
# sys.path.append('/home/etl_user/etl/dependencies/python-2.7.5/d_site_packages/site-packages-lib')
sys.path.append('/Users/yangjun/PycharmProjects/code/project/utilstool')
import utilstools
import yaml
class CouponEmail(object):
def __init__(self, conf_yaml_file):
self.deal_file = utilstools.DealFile()
self.current_pwd = self.deal_file.get_current_path()
print(self.current_pwd)
self.conf_yaml = open("{}/../conf/{}".format(self.current_pwd,conf_yaml_file), "r")
self.yaml_info = yaml.load(self.conf_yaml)
self.sender = self.yaml_info['email_info']['sender']
self.receivers = self.yaml_info['email_info']['receivers']
def __del__(self):
self.conf_yaml.close()
def send_eamli(self):
# 构造多用途邮件传输实例
message = MIMEMultipart()
message['From'] = self.sender
message['To'] = self.receivers
message['Subject'] = 'Coupon Data'
message['Date'] = formatdate()
# # 推荐使用html格式的正文内容,这样比较灵活,可以附加图片地址,调整格式等
with open("{}/../conf/{}".format(self.current_pwd, 'freemud.html'), 'r') as f:
content = f.read()
# # 设置html格式参数
part1 = MIMEText(content, 'html', 'utf-8')
message.attach(part1)
# 添加附件内容,添加两个xlsx文件
base_path, second_path, detail_file_list = self.deal_file.ergodic_directory('/Users/yangjun/PycharmProjects/code/project/python_email')
for detail_file in detail_file_list:
if not detail_file.endswith("txt"):
continue
basename = os.path.basename(detail_file)
with open('{}'.format(os.path.join(base_path, detail_file)), 'rb') as excell_content:
content = excell_content.read()
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('1', 'xlsx', filename='{}'.format(basename))
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment', filename='{}'.format(basename))
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的内容读进来:
mime.set_payload(content)
# 用Base64编码:
email.encoders.encode_base64(mime)
# 添加到MIMEMultipart:
message.attach(mime)
try:
# smtpObj = smtplib.SMTP()
# smtpObj.connect(self.yaml_info['email_info']['email_host'],25)
# 需要SSL认证
smtpObj = smtplib.SMTP_SSL(self.yaml_info['email_info']['email_host'])
smtpObj.login(self.yaml_info['email_info']['email_user'], self.yaml_info['email_info']['email_passwd'])
print(self.receivers.split(","))
smtpObj.sendmail(self.sender, self.receivers.split(","), message.as_string())
print('success')
smtpObj.quit()
except smtplib.SMTPException as e:
print('error', e)
# def list_dir(self, ):
if __name__ == '__main__':
coupon_email = CouponEmail("freemud.yaml")
coupon_email.send_eamli()
# cu = os.getcwd()
# print(cu)
# print(sys.argv[0])
../conf/freemud.yaml(邮件信息都需要改成自己的)
# freemud 基本配置文件
email_info:
sender: jimsyangdddd@163.com
# receivers: jimsyangdddd@163.com,jims.yang@dddd.com
receivers: jimsyangddddd@163.com, # 必须要有逗号,后面会根据逗号,将收件人进行切割,然后组成列表
email_host: 220.181.12.18
email_user: jimsyangddddd@163.com
email_passwd: yangjunjjjjj
../conf/freemud.html
<document><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Email Test</title>
</head>
<body>
<text>Dear All:</text>
<p> This is a reporting table.Please copy receviced </p>
</body>
</html>
</document>
````
../utilstool
<div class="se-preview-section-delimiter"></div>
```python
# -*- coding=utf-8
import os
import sys
sys.path.append("/home/etl_user/etl/dependencies/python-2.7.5/d_site_packages/site-packages")
sys.path.append('/home/etl_user/etl/dependencies/python-2.7.5/d_site_packages/site-packages-lib')
import pymysql
import paramiko
class DealFile(object):
def __init__(self):
pass
def ergodic_directory(self, directory_path):
# 遍历目录,拿到目录下的文件
for base_path,seconde_path, detail_file_list in os.walk(directory_path):
return base_path, seconde_path, detail_file_list
def get_current_path(self):
# os.getcwd()获取的是执行脚本所在的路径,比如脚本在/c/python/utilstools.py 在/c目录下执行脚本,os.path.getcwd() 返回/c,在/c/python 下执行,返回/c/python
# sys.path[0]无论在哪里执行脚本,都返回脚本所在路径/c/python
# 拿到包含文件的路径:/Users/yangjun/PycharmProjects/code/project/python_email/coupon_email_formal.py
# curennt_paht = sys.argv[0]
curennt_paht = sys.path[0]
return curennt_paht