python生成csv并发送邮件
python版本3.9.4
1、生成csv的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #make_csv.py# import csv def produce_csv(): # 1. 创建文件对象 f = open ( 'temp.csv' , 'w' , encoding = 'utf-8' , newline = '') # 2. 基于文件对象构建 csv写入对象 csv_writer = csv.writer(f) # 3. 构建列表头 csv_writer.writerow([ "姓名" , "年龄" , "性别" ]) # 4. 写入csv文件内容 csv_writer.writerow([ "l" , '18' , '男' ]) csv_writer.writerow([ "c" , '20' , '男' ]) csv_writer.writerow([ "w" , '22' , '女' ]) f.close() |
2、调用上面方法生成csv并发送邮件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #sed_mail.py#<br>#!/usr/bin/python3 from email.mime.multipart import MIMEMultipart import os import smtplib from email.mime.text import MIMEText from email.header import Header import make_csv #删除文件 try : os.remove( 'temp.csv' ) except : print ( "没有找到文件!" ) #调用make_csv文件的produce_csv方法生成文件 make_csv.produce_csv() # 第三方 SMTP 服务 mail_host = "smtp.exmail.qq.com" #设置服务器 mail_user = "user_sed@qq.com" #用户名 mail_pass = "passwd" #口令 sender = 'user_sed@qq.com' receivers = [ 'user_recevied@qq.com' ] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 print ( "1" ) message = MIMEMultipart() message.attach(MIMEText( '这是菜鸟教程Python 邮件发送测试……' , 'plain' , 'utf-8' )) message[ 'From' ] = Header( "菜鸟教程" , 'utf-8' ) message[ 'To' ] = Header( "测试" , 'utf-8' ) print ( "2" ) subject = 'Python SMTP 邮件测试' message[ 'Subject' ] = Header(subject, 'utf-8' ) print ( "3" ) # 构造附件1,传送当前目录下的 ces.xlsx 文件 att1 = MIMEText( open ( 'temp.csv' , 'rb' ).read(), 'base64' , 'utf-8' ) att1[ "Content-Type" ] = 'application/octet-stream' # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1[ "Content-Disposition" ] = 'attachment; filename="temp.csv"' message.attach(att1) try : smtpObj = smtplib.SMTP() print ( "4" ) smtpObj.connect(mail_host, 25 ) # 25 为 SMTP 端口号 print ( "5" ) smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print ( "邮件发送成功" ) except smtplib.SMTPException: print ( "Error: 无法发送邮件" ) print ( "6" ) |
做一个决定,并不难,难的是付诸行动,并且坚持到底。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)