python之smtplib发邮件

时间:2023-03-09 02:43:17
python之smtplib发邮件

第一版: 认证发信,不支持附件

#!/usr/bin/env python
# ---------------------------------------
# author : Geng Jie
# email : gengjie@outlook.com
#
# Create Time: 2016/3/13 15:21
# ----------------------------------------
import smtplib # 定义邮件服务器地址以及端口
SMTP_HOST = 'smtp.xxx.com'
SMTP_PORT = '25'
# 定义发件人,密码,收件人
MAIL_USER = 'xxx@xxx.com'
PASSWD = 'xxxxxxx'
MAIL_TO = 'xxxx@xxx.com'
# 定义邮件主题,内容
MAIL_SUB = '测试邮件'
MAIL_CON = '''
Hi, python: 最近好吗?好久不见.
''' message = """From: {0}
To: {1}
Subject: {2}
{3}
""".format(MAIL_USER, MAIL_TO, MAIL_SUB, MAIL_CON) try:
smtpObj = smtplib.SMTP(SMTP_HOST, SMTP_PORT)
smtpObj.login(MAIL_USER, PASSWD)
smtpObj.sendmail(MAIL_USER, MAIL_TO, message.encode('GBK'))
print('Successfully send email !')
smtpObj.quit() except smtplib.SMTPException as e:
print(e)
print('Error: unable to send mail !')

  

第二版,写成模块,可调用使用

 import smtplib
from email.mime.text import MIMEText
import socket class EasySendmail:
''' e = ClassMail.EasySendmail(Port=25, auth=True)
default smtp port : 25
# 默认smtp的端口是25,若需要更改则设置port=xxx
# 默认是认证发信,若要匿名发信则需设置auth=False
'''
def __init__(self, port=25, auth=True):
self.port = port
self.auth = auth @classmethod
def setmail(cls, host, sender, passwd, mail_to, mail_sub, content):
'''You must set attr:
Host : mailServer exp: smtp.163.com
Sender: mail from user
Passwd: user passwd
Mail_to: To user
Mail_sub: mail subject
content: message ''' cls.host = host
cls.sender = sender
cls.passwd = passwd
cls.mail_to = ';'.join(mail_to)
cls.mail_sub = mail_sub
cls.content = content @property
def sendmail(self):
'''sendmail: Start Connect server to send mail .'''
self.message = """From: {0}
To: {1}
MIME-Version: 1.0
Content-type: text/plain
Subject: {2} {3}
""".format(self.sender, self.mail_to, self.mail_sub, self.content) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
try:
s.connect((self.host, self.port))
# print('Connect {0}:{1} successfuly !'.format(self.host, self.port))
except Exception:
print('Error: Can connect {0}:{1} !'.format(self.host, self.port))
s.close() try:
print(self.auth)
smtpobj = smtplib.SMTP(self.host, self.port)
if self.auth is True:
smtpobj.login(self.sender, self.passwd)
smtpobj.sendmail(self.sender, self.mail_to, self.message.encode('GBK'))
print('Successfully send email !')
smtpobj.quit()
except smtplib.SMTPAuthenticationError as error:
print(error)
print('认证失败,请核对用户名和密码.')
except smtplib.SMTPException as error:
print(error)
print('Error: unable to send mail !')
except Exception as e:
print(e)

调用方法:

 #!/usr/bin/env python
# ---------------------------------------
# author : Geng Jie
# email : gengjie@outlook.com
#
# Create Time: 2016/3/14 13:19
# ---------------------------------------- import ClassMail if __name__ == '__main__':
# 初始化实例
# 默认smtp的端口是25,若需要更改则设置port=xxx
# 默认是认证发信,若要匿名发信则需设置auth=False
e = ClassMail.EasySendmail() # 定义邮件服务器
e.host = 'smtp.163.com'
# 定义发件人
e.sender = 'xxx@163.com'
# 定义发件人密码
e.passwd = '*******'
# 定义收件人,多个收件人,需用,号隔开
e.mail_to = ['xxxx@xxx.com'] # 定义邮件主题
e.mail_sub = 'EasyMail Test'
# 定义邮件正文
e.content = """Hi, Tony: How are you ?
"""
# 调用发信方法发送信件
e.sendmail