使用python3发送电子邮件,我之前在网上找了好几篇文章不论是都不行,最后在网上找到这篇文章了!
首先在163邮箱开启授权码
记住这个授权密码,我们在python代码里面用的就是这个密码
不然会出现这个报错
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : send1.py
# Author: HuXianyong
# Date : 2018/11/29
import smtplib
from email.header import Header
from email.mime.text import MIMEText
# 第三方 SMTP 服务
host = "smtp.163.com" # SMTP服务器
port = 465
user = "ghxy123@163.com" # 用户名
passWD = "13708556220" # 授权密码,非登录密码
sender = 'ghxy123@163.com' #发邮件人
receivers = 'ghxy123@163.com,ghuxy123@163.com' #收邮件人
content = '''
这个是邮件内容,
你想写些什么就写些什么!
''' #邮件内容
subject = '邮件主题' # 邮件主题
# meg['Subject'] = subject #这个方法和下面的一样可以发送邮件
def send_email1():
meg = MIMEText(content+' \n send_email1', 'plain', 'utf-8') # 内容, 格式, 编码
meg['From'] = user # 这两种方法都一样的
# meg['From'] = "{}".format(user)
meg['To'] = receivers
meg['Subject'] = subject+' send_email1'
# msg['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP_SSL(host, port) # 启用SSL发信, 端口一般是465
smtpObj.login(user, passWD) # 登录验证
smtpObj.sendmail(sender, receivers, meg.as_string()) # 发送
print("邮件1发送成功!")
except smtplib.SMTPException as e:
print(e)
def send_email2(host, user, passWD, receivers, subject, content):
email_client = smtplib.SMTP(host)
email_client.login(user, passWD)
# create msg
msg = MIMEText(content+'\n这个是send_email2', 'plain', 'utf-8')
msg['From'] = user
msg['To'] = receivers
msg['Subject'] = Header(subject+' send_email2', 'utf-8')
email_client.sendmail(user, receivers, msg.as_string())
email_client.quit()
# print(msg)
print('邮件2发送成功!')
if __name__ == '__main__':
send_email1()
send_email2(host, user, passWD, receivers, subject, content)
文章借鉴
http://blog.csdn.net/sunhuaqiang1/article/details/70833199
转载于:https://blog.51cto.com/853056088/2073898