python实现发送邮件

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", "邮件主题", "邮件内容")



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值