Python 发送邮件示例代码
要使用Python发送邮件,可以使用smtplib库和email库。以下是一个简单的示例代码: 1. 首先,导入所需的库: ```python import smtplib from email.mime.text import MIMEText from email.header import Header ``` 2. 然后,设置发件人和收件人的邮箱地址、主题和正文: ```python sender = 'your_email@example.com' receiver = 'receiver_email@example.com' subject = '邮件主题' content = '邮件正文' ``` 3. 接下来,创建MIMEText对象并设置邮件内容: ```python message = MIMEText(content, 'plain', 'utf-8') message['From'] = Header(sender, 'utf-8') message['To'] = Header(receiver, 'utf-8')
添加附件函数:
defadd_att(msg,file_path,filename):att=MIMEText(open(file_path,'rb').read(),'base64','utf-8')#rb以二进制方式读取att["Content-Type"]='application/octet-stream'att.add_header('Content-Disposition','attachment',filename=filename)#将附件添加到MIMEMultipart中msg.attach(att)
发送方法:
defsend_email_test():mail={'host':'smtp.XXXXX.com','user':'XXX@XXX.com','password':'******'}sender=mail['user']receivers='111@111.com'#单个收件人#receivers='111@111.com,222@222.com'#多个收件人subject='邮件来了'nickname='我是昵称'message=MIMEMultipart()message['From']='%s<%s>'%(Header(nickname,'UTF-8'),sender)message['To']=Header(receivers,'gb2312')message['Subject']=Header(subject).encode()message['Message-id']=email.utils.make_msgid()message["Accept-Language"]="zh-CN"message["Accept-Charset"]="ISO-8859-1,utf-8"msg='''<html><h2>Hello</h2></html>'''html=MIMEText(msg,_subtype='html',_charset='UTF-8')#发送HTML邮件message.attach(html)#添加#添加当前目录下附件1.xlsx作为邮件附件file_path=os.path.join('附件1.xlsx')file_name='邮件显示附件名.xlsx'add_att(message,file_path,file_name)smtp=smtplib.SMTP()#使用SSL连接smtp服务器,否则使用.SMTPsmtp.connect(mail['host'],25)#主机,端口,如果使用SSL为465,否则25smtp.login(mail['user'],mail['password'])#用户名,密码smtp.sendmail(sender,receivers,message.as_string())#单个收件人#smtp.sendmail(sender,receivers.split(','),message.as_string())#多个收件人smtp.quit()print('完成邮件发生任务')