Python发送带附件的邮件

时间:2022-05-24 16:15:55

看别人的博客就不要在往别人的邮箱里发东西了行不行, 有点素质可以吗!!! 写出来分享还不知道珍惜!!!!!

#-*-encoding:utf-8 -*-
import os
import smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr mail_host="smtp.163.com"#使用的邮箱的smtp服务器地址,这里是163的smtp地址
mail_user=raw_input("你的163邮箱: ")#发送方邮箱
mail_pass=raw_input("邮箱授权码: ") #授权码
mail_postfix="163.com"#邮箱的后缀,网易就是163.com
mail_from = raw_input("来自: ") #发送方昵称
mail_sub = raw_input("邮件主题: ") #邮件主题
mail_content = raw_input("邮件主体内容: ") me=mail_from+"<"+mail_user+">" msg_attach = MIMEMultipart() msg_attach['Subject'] = mail_sub
msg_attach['From'] = me
to_list = map(None,raw_input("mail_to: ").split(" "))#可以群发
msg_attach['To'] = ",".join(to_list)#将收件人列表以‘,’分隔 # 邮件正文是MIMEText(content,'plain','utf-8')
msg_attach.attach(MIMEText(mail_content,'plain','utf-8')) #print "---1---",os.getcwd() #打印出当前工作目录 #pic_source = '/home/xushukui/图片/123.jpg' #输入图片的目录的时候千万不要带引号,不然会报错, 图片名字之间不能有间隔(比如空格), 不然切割的时候会报错
pic_source = raw_input("请输入图片的目录,千万不要带引号, 不然会报错: ") #先对pic_source进行切割, pwd是列表, 然后用"/".join(pwd) 把列表里面的内容连起来, 则cwd即为图片的目录, 然后进行目录切换,但是图片名字是中文接收的时候乱码问题还没解决, 已经解决的网友可以在博客下面告诉我一下方法吗,十分感谢
pwd = pic_source.split("/")[:-1]
cwd = "/".join(pwd) os.chdir(cwd)
#print "---2---",os.getcwd() pic_name = pic_source.split('/')[-1] #图片名
pic_suffix = pic_name.split('.')[-1] #图片后缀 # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open(pic_source, 'rb') as f:
# 设置附件的MIME和文件名,这里是gif类型:
mime = MIMEBase('image', pic_suffix, filename=pic_name)
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment', filename=pic_name)
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime) # 添加到MIMEMultipart:
msg_attach.attach(mime) def main():
try:
server = smtplib.SMTP()
server.connect(mail_host)#连接服务器
server.login(mail_user,mail_pass)#登录操作
server.sendmail(me, to_list, msg_attach.as_string())
server.close()
return True
except Exception, e:#捕捉异常,并将异常对象输出
print str(e)
return False if main():
print "done!"
else:
print "failed!"
本文转自:http://blog.csdn.net/zm2714/article/details/7993732

可采用email模块发送电子邮件附件。发送一个未知MIME类型的文件附件其基本思路如下:

构造MIMEMultipart对象做为根容器
构造MIMEText对象做为邮件显示内容并附加到根容器
构造MIMEBase对象做为文件附件内容并附加到根容器
  a. 读入文件内容并格式化
  b. 设置附件头
设置根容器属性
得到格式化后的完整文本
用smtp发送邮件
# -*- coding: utf-8 -*-
import smtplib
import os.path
import mimetypes
import email.MIMEText
import email.MIMEBase
import email.MIMEImage
import email.MIMEMultipart From = "你的163邮箱"
To = "你的qq邮箱"
file_name = "/home/xushukui/xsk/xsk123.png.jpeg"#附件名 server = smtplib.SMTP("smtp.163.com") server.login("你的163邮箱","xxxx") #仅smtp服务器需要验证时(账号,密码)
# 构造MIMEMultipart对象做为根容器
main_msg = email.MIMEMultipart.MIMEMultipart() # 构造MIMEText对象做为邮件显示内容并附加到根容器
text_msg = email.MIMEText.MIMEText("this is a test text to text mime",_charset="utf-8")
main_msg.attach(text_msg) # 构造MIMEBase对象做为文件附件内容并附加到根容器
ctype,encoding = mimetypes.guess_type(file_name)
if ctype is None or encoding is not None:
ctype='application/octet-stream'
maintype,subtype = ctype.split('/',1)#分割返回两个值
#print maintype,subtype (可以输出看看)
file_msg=email.MIMEImage.MIMEImage(open(file_name,'rb').read(),subtype)
print ctype,encoding #火狐会将jpg、jpeg翻译成image/jpeg,png翻译成image/png ## 设置附件头
basename = os.path.basename(file_name)#os.path.basename(path) #返回文件名
#Content-disposition就是当用户想把请求所得内容存为一个文件的提供一个默认的文件名
file_msg.add_header('Content-Disposition','attachment', filename = basename)#修改邮件头
main_msg.attach(file_msg) # 设置根容器属性
main_msg['From'] = From
main_msg['To'] = To
main_msg['Subject'] = "attach test "
main_msg['Date'] = email.Utils.formatdate( ) # 得到格式化后的完整文本
fullText = main_msg.as_string( ) # 用smtp发送邮件
try:
server.sendmail(From, To, fullText)
finally:
server.quit() #application/octet-stream
#1.只能提交二进制,而且只能提交一个二进制,
#如果提交文件的话,只能提交一个文件,后台接收参数只能有一个,而且只能是流(或者字节数组) #2.属于HTTP规范中Content-Type的一种 #3.很少使用
第二种方法
#!usr/bin/python
#-*- coding:utf-8 -*-
import smtplib
import os.path
import mimetypes
import email.MIMEText
import email.MIMEBase
import email.MIMEImage
import email.MIMEMultipart mailer_name=raw_input("name: ")
From = raw_input("163 mail address: ")
password = raw_input("password: ")
to_list = map(None,raw_input("to: ").split(" "))
file_name = "/home/xushukui/图片/nonexistent.jpg" server = smtplib.SMTP("smtp.163.com")
server.login(From,password) main_msg = email.MIMEMultipart.MIMEMultipart() text_msg = email.MIMEText.MIMEText("不存在的",_charset = "utf-8")
main_msg.attach(text_msg) ctype,encoding = mimetypes.guess_type(file_name)
if ctype is None or encoding is not None:
ctype='application/octet-stream'
maintype,subtype = ctype.split('/',1) file_msg = email.MIMEImage.MIMEImage(open(file_name,'rb').read(),subtype)
#print ctype,encoding basename=os.path.basename(file_name) file_msg.add_header('Content-Disposition','attachment',filename=basename)
main_msg.attach(file_msg) main_msg['From']= mailer_name+"<"+From+">"
main_msg['To'] = ",".join(to_list)
main_msg['Subject'] = "附带一张图片" main_msg['Date'] = email.Utils.formatdate() fullText = main_msg.as_string() try:
server.sendmail(From , to_list,fullText)
print "done!"
finally:
server.quit() #运行结果:

Python发送带附件的邮件