Python smtplib实现发送邮件功能

作者:Johnny 时间:2021-02-14 20:07:26 

本文实例为大家分享了Python smtplib发送邮件功能的具体代码,供大家参考,具体内容如下

解决之前版本的问题,下面为最新版


#!/usr/bin/env python
# coding:gbk

"""
FuncName: sendemail.py
Desc: sendemail with text,image,audio,application...
Date: 2016-06-20 10:30
Home: http://blog.csdn.net/z_johnny
Author: johnny
"""

from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.utils import COMMASPACE
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
import ConfigParser
import smtplib
import os

class MyEmail:
def __init__(self, email_config_path, email_attachment_path):
 """
 init config
 """
 config = ConfigParser.ConfigParser()
 config.read(email_config_path)
 self.attachment_path = email_attachment_path

self.smtp = smtplib.SMTP()
 self.login_username = config.get('SMTP', 'login_username')
 self.login_password = config.get('SMTP', 'login_password')
 self.sender = config.get('SMTP', 'login_username') # same as login_username
 self.receiver = config.get('SMTP', 'receiver')
 self.host = config.get('SMTP', 'host')
 #self.port = config.get('SMTP', 'port')  发现加入端口后有时候发邮件出现延迟,故暂时取消

def connect(self):
 """
 connect server
 """
 #self.smtp.connect(self.host, self.port)
 self.smtp.connect(self.host)

def login(self):
 """
 login email
 """
 try:
  self.smtp.login(self.login_username, self.login_password)
 except:
  raise AttributeError('Can not login smtp!!!')

def send(self, email_title, email_content):
 """
 send email
 """
 msg = MIMEMultipart()     # create MIMEMultipart
 msg['From'] = self.sender    # sender
 receiver = self.receiver.split(",")  # split receiver to send more user
 msg['To'] = COMMASPACE.join(receiver)
 msg['Subject'] = email_title   # email Subject
 content = MIMEText(email_content, _charset='gbk') # add email content ,coding is gbk, becasue chinese exist
 msg.attach(content)

for attachment_name in os.listdir(self.attachment_path):
  attachment_file = os.path.join(self.attachment_path,attachment_name)

with open(attachment_file, 'rb') as attachment:
   if 'application' == 'text':
    attachment = MIMEText(attachment.read(), _subtype='octet-stream', _charset='GB2312')
   elif 'application' == 'image':
    attachment = MIMEImage(attachment.read(), _subtype='octet-stream')
   elif 'application' == 'audio':
    attachment = MIMEAudio(attachment.read(), _subtype='octet-stream')
   else:
    attachment = MIMEApplication(attachment.read(), _subtype='octet-stream')

attachment.add_header('Content-Disposition', 'attachment', filename = ('gbk', '', attachment_name))
  # make sure "attachment_name is chinese" right
  msg.attach(attachment)

self.smtp.sendmail(self.sender, receiver, msg.as_string()) # format msg.as_string()

def quit(self):
 self.smtp.quit()

def send():
import time
ISOTIMEFORMAT='_%Y-%m-%d_%A'
current_time =str(time.strftime(ISOTIMEFORMAT))

email_config_path = './config/emailConfig.ini' # config path
email_attachment_path = './result'    # attachment path
email_tiltle = 'johnny test'+'%s'%current_time # as johnny test_2016-06-20_Monday ,it can choose only file when add time
email_content = 'python发送邮件测试,包含附件'

myemail = MyEmail(email_config_path,email_attachment_path)
myemail.connect()
myemail.login()
myemail.send(email_tiltle, email_content)
myemail.quit()

if __name__ == "__main__":
# from sendemail import SendEmail
send()

配置文件emailConfig.ini

路径要与程序对应


;login_username : 登陆发件人用户名
;login_password : 登陆发件人密码
;host:port : 发件人邮箱对应的host和端口,如:smtp.163.com:25 和 smtp.qq.com:465
;receiver : 收件人,支持多方发送,格式(注意英文逗号): 123456789@163.com,zxcvbnm@qq.com

[SMTP]
login_username = johnny@163.com
login_password = johnny
host = smtp.163.com
port = 25
receiver = johnny1@qq.com,johnny2@163.com,johnny3@gmail.com

之前版本出现的问题:


#!/usr/bin/env python
#coding: utf-8

'''''
FuncName: smtplib_email.py
Desc: 使用smtplib发送邮件
Date: 2016-04-11 14:00
Author: johnny
'''

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.utils import COMMASPACE,formatdate
from email import encoders

def send_email_text(sender,receiver,host,subject,text,filename):

assert type(receiver) == list

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = COMMASPACE.join(receiver)
msg['Subject'] = subject
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(text))     #邮件正文内容

for file in filename:      #邮件附件
 att = MIMEBase('application', 'octet-stream')
 att.set_payload(open(file, 'rb').read())
 encoders.encode_base64(att)
 if file.endswith('.html'):    # 若不加限定,jpg、html等格式附件是bin格式的
  att.add_header('Content-Disposition', 'attachment; filename="今日测试结果.html"')   # 强制命名,名称未成功格式化,如果可以解决请联系我
 elif file.endswith('.jpg') or file.endswith('.png') :
  att.add_header('Content-Disposition', 'attachment; filename="pic.jpg"')
 else:
  att.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
 msg.attach(att)

smtp = smtplib.SMTP(host)  
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(username,password)
smtp.sendmail(sender,receiver, msg.as_string())
smtp.close()

if __name__=="__main__":
sender = 'qqq@163.com'
receiver = ['www@qq.com']
subject = "测试"
text = "johnny'lab test"
filename = [u'测试报告.html','123.txt',u'获取的信息.jpg']
host = 'smtp.163.com'
username = 'qqq@163.com'
password = 'qqq'
send_email_text(sender,receiver,host,subject,text,filename)

已测试通过,使用Header并没有变成“头”,故未使用

若能解决附件格式为(html、jpg、png)在邮箱附件中格式不为“bin”的请联系我,希望此对大家有所帮助,谢谢(已解决,见上面最新版

点击查看:Python 邮件smtplib发送示例 

来源:https://blog.csdn.net/z_johnny/article/details/51146300

标签:Python,smtplib
0
投稿

猜你喜欢

  • [译]“我心中的ebay”

    2008-06-04 12:09:00
  • 在MySQL数据库中如何来复位根用户的密码

    2008-12-03 16:57:00
  • python实现两个一维列表合并成一个二维列表

    2023-08-06 12:59:44
  • 如何在Django配置文件里配置session链接

    2022-09-08 18:17:33
  • 在DOS界面如何运行python的py文件

    2022-05-01 16:39:33
  • sqlserver主键设计的注意点

    2012-08-21 10:42:44
  • python递归实现快速排序

    2023-08-26 22:46:27
  • PHP 检查扩展库或函数是否可用的代码

    2023-07-22 23:34:34
  • 如何解决python多种版本冲突问题

    2023-12-28 06:41:17
  • Python实现可获取网易页面所有文本信息的网易网络爬虫功能示例

    2023-08-21 18:51:04
  • python 的 openpyxl模块 读取 Excel文件的方法

    2023-02-23 14:41:56
  • SNS用户体验和互动性浅析

    2011-01-17 17:56:00
  • python字符串连接方法分析

    2021-12-24 16:27:10
  • 关于设计规范

    2008-06-02 13:10:00
  • 如何固定表格的标题行和标题列

    2007-09-20 13:03:00
  • Python OpenCV实现视频追踪

    2021-09-29 23:04:27
  • apache集成php5.6方法分享

    2023-09-06 09:03:54
  • IE6,7下实现white-space:pre-wrap;

    2009-12-31 18:30:00
  • asp ajax注册验证之 防止用户名输入空格

    2011-03-11 11:17:00
  • php中mysql连接方式PDO使用详解

    2023-11-06 02:46:43
  • asp之家 网络编程 m.aspxhome.com