#-*-coding:utf-8-*- import smtplib from smtplib import SMTP_SSL from email.mime.text import MIMEText from email.header import Header #定义一个字典存储发送和接收,邮箱账号密码主题、内容及编码相关信息 mail_info = { "from": "[email protected]", #发件人 "to": "[email protected]", #收件人 "hostname": "smtp.qq.com", #qq smtp服务器 "username": "[email protected]", #邮箱账号 "password": "xxxxxxxxxxxx", #邮箱密码,这个密码为qq邮箱授权码,具体设置请见:http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256 "subject": "测试一下发邮件", #邮件主题 "mail_text": "我只想测试下邮件能否发送",#邮件内容 "mail_encoding": "utf-8" #编码格式 } #使用MIME格式传送内容 msg=MIMEText(mail_info[‘mail_text‘],"plain",mail_info[‘mail_encoding‘]) #设置邮件主题 msg[‘Subject‘] = Header(mail_info[‘subject‘],mail_info[‘mail_encoding‘]) #设置邮件发件人 msg["from"] = mail_info["from"] #设置收件人 msg["to"] = mail_info["to"] #创建一个smtp对象 smtp=SMTP_SSL() #smtp.set_debuglevel(1) try: #连接qq smtp服务器 smtp.connect(mail_info[‘hostname‘]) #使用账号密码登录邮箱 smtp.login(mail_info[‘username‘],mail_info[‘password‘]) #发送邮件 smtp.sendmail(mail_info[‘from‘],mail_info[‘to‘],msg.as_string()) #关闭邮件对象 smtp.quit() except smtplib.SMTPAuthenticationError as e: print e else: print "发送成功"
时间: 2024-10-11 04:00:09