import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
class sendEmail():
def __init__(self, userID, userPwd):
'''
:param userID: 发件人邮箱账号
:param userPwd: 发件人邮箱客户端授权码
'''
self.sendEmailUserID = userID
self.sendEmailUserPasswd = userPwd
def sendEmail(self, acceptEmailUserID, sendEmailSubject,sendEmailMsg):
'''
:param acceptEmailUserID: 收件人邮箱账号
:param sendEmailSubject: 邮件主题
:param sendEmailMsg: 邮件内容
:return: True发送成功, False发送失败
'''
ret = True
try:
acceptEmailUserName = sendEmail.getUserName(acceptEmailUserID)
sendEmailUserName = sendEmail.getUserName(self.sendEmailUserID)
msg = MIMEText(sendEmailMsg, 'plain', 'utf-8')
msg['From'] = formataddr([sendEmailUserName, self.sendEmailUserID]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['To'] = formataddr([acceptEmailUserName, acceptEmailUserID]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['Subject'] = sendEmailSubject # 邮件的主题,也可以说是标题
server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是465
server.login(self.sendEmailUserID, self.sendEmailUserPasswd) # 括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(self.sendEmailUserID, [acceptEmailUserID, ], msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit() # 关闭连接
except Exception:
ret = False
return ret
@staticmethod
def getUserName(emailId):
'''
:param emailId:
:return:
'''
emailName = emailId.split("@")[0]
return emailName
if __name__ == '__main__':
sendEmailUserID = "*******@qq.com"
sendEmailUserPasswd = "*********"
sendEmail = sendEmail(sendEmailUserID, sendEmailUserPasswd)
sendEmail.sendEmail("******@163.com", "邮件主题", "邮件内容")
python实现发送邮件
最新推荐文章于 2022-04-25 19:11:36 发布