如题,使用 python 编写了个发送邮件的 Demo 。邮件发送后,用 Foxmail 能够正常收的到。
但是收件人一栏显示的收件邮箱很奇怪,如下图,一整个收件邮箱被按字符拆分为好多个小邮箱,小邮箱的那域名我也没见过。
原本收件邮箱应该显示是 [email protected]
不知道有大佬遇到过这种情况没,请教下
下面是源码(看着没毛病):
# 编译日期:2019-10-14 15:01:36
# coding=utf-8
import os
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 发送邮件(附件)
# email_user: 发件人
# email_pass: 密码
# receivers:收件人列表,例:['[email protected]','[email protected]']
# filepath: 文件地址 如:r'D:\分行查询支行卷别库存 Excel\作文.xlsx'
def sendEmail(email_user, email_pass, receivers, filepath):
mail_host = '10.10.10.10' # 设置服务器地址
sender = email_user + '@xxx.com.cn' # 发件人邮箱
# 创建一个带附件的实例
message = MIMEMultipart()
# 设置发件人、收件人
message['From'] = sender
message['To'] = ", ".join(receivers)
# 设置邮件主题
message['Subject'] = Header('查冻扣报备文件', 'utf-8')
# 邮件正文
message.attach(MIMEText('查冻扣报备文件已发送,请查看附件!', 'plain', 'utf-8'))
# 构造附件
xlsx = MIMEApplication(open(filepath,'rb').read())
xlsx['Content-Type'] = 'application/octet-stream'
filename = os.path.basename(filepath)
xlsx.add_header('Content-Disposition', 'attachment', filename=Header(filename, 'utf-8').encode())
message.attach(xlsx)
try:
smtpObj = smtplib.SMTP(mail_host, 1025)
smtpObj.login(email_user, email_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功,收件人:" + str(receivers) + "\n 附件地址:" + str(filepath))
except smtplib.SMTPException as e:
print("邮件发送失败,收件人:" + str(receivers) + "\n 附件地址:" + str(filepath))
print(e)
1
j0hnj 2020-07-20 17:06:50 +08:00
`sendEmail` 是怎么调用的呢?我猜可能是把 `receivers` 传成 str 了
|
2
Vegetable 2020-07-20 17:13:32 +08:00
message['To'] = Header(",".join(receivers), 'utf-8')
|
3
Aliencn 2020-07-20 17:31:21 +08:00 1
|
4
BryceBu 2020-07-20 17:34:02 +08:00
第二个参数是 list 不是 str 噢
|
5
Kvip OP |
6
julyclyde 2020-07-21 10:47:02 +08:00
@Kvip 因为其实并没有传错对象啊。sendmail 函数的参数里面,发送目标是 receivers 而不是 ", ".join(receivers)
|
7
j0hnj 2020-07-21 14:30:47 +08:00
@Kvip #5 决定能不能收到邮件的是 `sendmail` 的 `to_addrs` 参数,这个参数可以有特殊处理,如果是 str 的话,会变成 to_addrs = [to_addrs], 代码在这里:
https://github.com/python/cpython/blob/master/Lib/smtplib.py#L873-L874 而 message['To'] 是决定一封邮件里收件人那一列的内容的,这里其实是可以随便写的,并不决定邮件发给谁。 |
8
jenas999 2020-07-25 23:12:20 +08:00
message['To'] = ", ".join(receivers)
逗号改成分号试试,群发邮件中间貌似是分号隔开 message['To'] = "; ".join(receivers) |