1、发送普通文字邮件
from email.mime.text import MIMEText msg = MIMEText('hello, send by Python...', 'plain', 'utf-8') # 输入Email地址和口令: from_addr = 'xxxxx@163.com' password = 'xxxxx' #邮箱开启smtp服务获取的授权码 # 输入收件人地址: to_addr = 'xxxxxx@163.com' # 输入SMTP服务器地址: smtp_server = 'smtp.163.com' import smtplib server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25 server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
2、发送带附件邮件
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header sender = 'xxxxxx@163.com' password = 'xxxxxx' receivers = ['xxxxxx@163.com'] # 接收邮件 # 创建一个带附件的实例 message = MIMEMultipart() message['From'] = Header("测试啦啦啦", 'utf-8') message['To'] = Header("测试", 'utf-8') subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') # 邮件正文内容 message.attach(MIMEText('邮件发送测试……', 'plain', 'utf-8')) # 构造附件1,传送当前目录下的 t1.py 文件 att1 = MIMEText(open('t1.py', 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = 'attachment; filename="t1.py"' message.attach(att1) try: smtpObj = smtplib.SMTP('smtp.163.com') smtpObj.login(sender,password) # 测试时需要登录 smtpObj.sendmail(sender, receivers, message.as_string()) print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件")