1. python发送邮件POP3
# coding: utf-8
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
from email.mime.text import MIMEText
import pathlib
def send_mail(username, passwd, recv, title, content, mail_host='smtp.163.com', port=25, file=None):
'''
发送邮件函数,默认使用163smtp
:param username: 邮箱账号 xx@163.com
:param passwd: 邮箱密码
:param recv: 邮箱接收人地址,多个账号以逗号隔开
:param title: 邮件标题
:param content: 邮件内容
:param mail_host: 邮箱服务器
:param port: 端口号
:return:
'''
if file:
msg = MIMEMultipart()
# 构建正文
part_text = MIMEText(content)
msg.attach(part_text) # 把正文加到邮件体里面去
# 构建邮件附件
part_attach1 = MIMEApplication(open(file, 'rb').read()) # 打开附件
part_attach1.add_header('Content-Disposition', 'attachment', filename =pathlib.Path(file).name) # 为附件命名
msg.attach(part_attach1) # 添加附件
else:
msg = MIMEText(content) # 邮件内容
msg['Subject'] = title # 邮件主题
msg['From'] = username # 发送者账号
msg['To'] = recv # 接收者账号列表
smtp = smtplib.SMTP(mail_host, port=port)
smtp.login(username, passwd) # 登录
smtp.sendmail(username, recv, msg.as_string())
smtp.quit()
send_address="发件人@163.com"
send_password=input('请输入密码:')
receive_address="收件人@163.com"
title="标题"
content="Hi,你好!这封邮件是python发送的"
attachfilepath="d:\\test.xlsx"
send_mail(send_address, send_password, receive_address, title,content ,file=attachfilepath)
print('success')
2. python发送邮件Exchange
from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody,FileAttachment
import pathlib
send_password=input('请输入密码') # input 手动输入
send_user='公司邮箱域.cic.cn\个人用户名' # 公司邮箱域/用户名(不带后面@)
# send_address :发送方地址
# receive_address :发送方地址
# subject :主题
# body :正文
# attachPath :附件路径
def Email(send_address,receive_address, subject, body,attachPath=None):
creds = Credentials(send_user, send_password)
account = Account(send_address, credentials=creds, autodiscover=True)
m = Message(
account=account,
subject=subject,
body=HTMLBody(body),
to_recipients = [Mailbox(email_address=receive_address)]
)
#添加附件
if attachPath:
myfile = FileAttachment(name=pathlib.Path(attachPath).name, content=open(attachPath,'rb').read())
m.attach(myfile)
m.send()
send_address="发件人@cic.cn"
receive_address="收件人@163.com"
title="标题"
content="Hi,你好!这封邮件是python发送的"
attachfilepath="d:\\test.xlsx"
Email(send_address,receive_address, title, content,attachfilepath)
print(receive_address+':'+'发送成功')
未完待续...
参考:站在巨人的肩上python发送带附件POP3:https://zhuanlan.zhihu.com/p/69817786zhuanlan.zhihu.compython发送 ExchangePython3.5 执行发邮件Exchangelib(=)www.cnblogs.comCSDN-专业IT技术社区-登录blog.csdn.net
#字典初始化1
emailDict={
"key1":"value1",
"key2":"value2"
}
#字典初始化2
emailDict1={}
emailDict1["key1"]="value1"
#遍历key
for key in emailDict1:
print(key+':'+emailDict1[key])
#遍历value
for value in emailDict.values():
print(value)
#遍历key+value
for (key,value) in emailDict.items():
print(key+':'+value)