python使用网易邮箱服务发邮件报554

错误信息

(554, b’DT:SPM 163 smtp14,EsCowACnnOp_kdBflbfuIg–.5619S2 1607504256,please see http://mail.163.com/help/help_spam_16.htm?ip=61.140.181.56&hostid=smtp14&time=1607504256’)

出错代码:

import os
import smtplib
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


class SendEmail(object):
    def __init__(self, username, passwd, sender, recv, title, content,
                 file=None, ssl=False, email_host='smtp.163.com',
                 port=25, ssl_port=465):
        """
        :param username: 用户名
        :param passwd: 密码
        :param recv: 收件人,多个收件人传list  ['a@qq.com','b@qq.com]
        :param title: 邮件标题
        :param content: 邮件正文
        :param file:  附件路径,如果不在当前目录下,要写绝对路径
        :param ssl: 是否安全链接
        :param email_host: smtp服务器地址
        :param port: 普通端口
        :param ssl_port: 安全链接端口
        """
        self.username = username
        self.passwd = passwd
        self.sender = sender
        self.recv = recv
        self.title = title
        self.content = content
        self.file = file
        self.email_host = email_host
        self.port = port
        self.ssl = ssl
        self.ssl_port = ssl_port

    def send_email(self):
        msg = MIMEMultipart()
        # 发送邮件对象
        if self.file:
            file_name = os.path.split(self.file)[-1]   # 只取文件名,不取路径
            try:
                f = open(self.file, 'rb').read()
            except Exception as e:
                raise Exception('附件打不开!!!')
            else:
                att = MIMEText(f, "base64", "utf-8")
                att["Content-Type"] = 'application/octet-stream'
                new_file_name = '=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
                att["Content-Type"] = 'attachment; filename="%s"' % new_file_name
                msg.attach(att)

        msg.attach(MIMEText(self.content))    # 邮件正文的内容
        msg["Subject"] = self.title       # 邮件主题
        msg['From'] = self.sender    # 发送者账号
        msg['To'] = ','.join(self.recv)   # 接收者账号列表

        if self.ssl:
            self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.ssl_port)
        else:
            self.smtp = smtplib.SMTP(self.email_host, port=self.port)

        try:
            self.smtp.login(self.username, self.passwd)
            self.smtp.sendmail(self.username, self.recv, msg.as_string())
            print('成功了。。')
        except Exception as e:
            print('出错了..', e)


if __name__ == '__main__':
    m = SendEmail(
        username='17746506075@163.com',
        passwd='FJRMTAWBWHWVWURK',
        sender='17746506075@163.com',
        recv=['1401230275@qq.com'],
        title='123',
        content='测试邮件发送',
        file=r'F:\图片\abc.jpg',
        ssl=True
    )
    m.send_email()
运行结果
	D:\自学python\python基础\API_Test\venv\Scripts\python.exe D:/自学python/python基础/API_Test/common/send_email.py
	出错了.. (554, b'DT:SPM 163 smtp14,EsCowACnnOp_kdBflbfuIg--.5619S2 1607504256,please see http://mail.163.com/help/help_spam_16.htm?ip=61.140.181.56&hostid=smtp14&time=1607504256')
	
	Process finished with exit code 0

原 因是:

原来这时因为网易将我发的邮件当成了垃圾邮件!

解决办法是:这时候你只要在发邮件的时候抄送上自己,就再也不会报这个错误了!

import os
import smtplib
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


class SendEmail(object):
    def __init__(self, username, passwd, sender, recv, title, content,
                 file=None, ssl=False, email_host='smtp.163.com',
                 port=25, ssl_port=465):
        """
        :param username: 用户名
        :param passwd: 密码
        :param recv: 收件人,多个收件人传list  ['a@qq.com','b@qq.com]
        :param title: 邮件标题
        :param content: 邮件正文
        :param file:  附件路径,如果不在当前目录下,要写绝对路径
        :param ssl: 是否安全链接
        :param email_host: smtp服务器地址
        :param port: 普通端口
        :param ssl_port: 安全链接端口
        """
        self.username = username
        self.passwd = passwd
        self.sender = sender
        self.recv = recv
        self.title = title
        self.content = content
        self.file = file
        self.email_host = email_host
        self.port = port
        self.ssl = ssl
        self.ssl_port = ssl_port

    def send_email(self):
        msg = MIMEMultipart()
        # 发送邮件对象
        if self.file:
            file_name = os.path.split(self.file)[-1]   # 只取文件名,不取路径
            try:
                f = open(self.file, 'rb').read()
            except Exception as e:
                raise Exception('附件打不开!!!')
            else:
                att = MIMEText(f, "base64", "utf-8")
                att["Content-Type"] = 'application/octet-stream'
                new_file_name = '=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
                att["Content-Type"] = 'attachment; filename="%s"' % new_file_name
                msg.attach(att)

        msg.attach(MIMEText(self.content))    # 邮件正文的内容
        msg["Subject"] = self.title       # 邮件主题
        msg['From'] = self.sender    # 发送者账号
        msg['To'] = ','.join(self.recv)   # 接收者账号列表

        if self.ssl:
            self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.ssl_port)
        else:
            self.smtp = smtplib.SMTP(self.email_host, port=self.port)

        try:
            self.smtp.login(self.username, self.passwd)
            self.smtp.sendmail(self.username, self.recv, msg.as_string())
            print('成功了。。')
        except Exception as e:
            print('出错了..', e)


if __name__ == '__main__':
    m = SendEmail(
        username='17746506075@163.com',
        passwd='FJRMTAWBWHWVWURK',
        sender='17746506075@163.com',
        recv=['1401230275@qq.com', '17746506075@163.com'],
        title='123',
        content='测试邮件发送',
        file=r'F:\图片\abc.jpg',
        ssl=True
    )
    m.send_email()
运行结果为:
D:\自学python\python基础\API_Test\venv\Scripts\python.exe D:/自学python/python基础/API_Test/common/send_email.py
成功了。。

Process finished with exit code 0
Python中,imaplib模块用于访问IMAP4(Internet Message Access Protocol version 4服务器,以便读取、管理电子邮件。如果你想要通过imaplib使用网易邮箱接收邮件,首先你需要满足以下几个条件: 1. **设置邮箱授权码**:由于网易等一些邮箱服务会启用SMTP/IMAP的二次验证,你需要获取一个专用的授权码,通常是在邮箱的安全中心设置里生成。 2. **安装必要的库**:确保已经安装了`imaplib`以及如`smtplib`(用于发送授权码)这样的基础库。如果没有,可以使用pip安装: ``` pip install imaplib smtplib ``` 3. **配置连接信息**: - `host`: 网易邮箱的IMAP服务器地址,通常是`imap.163.com`或`imapsmtp.163.com`; - `port`: 根据网易邮箱是否开启SSL/TLS,可能是993(加密)或143(非加密); - `username` 和 `password` 或 `auth_code`(授权码)。 下面是一个简单的例子,演示如何使用imaplib从网易邮箱接收邮件: ```python import imaplib import email from email.header import decode_header # 连接到IMAP服务器 mail = imaplib.IMAP4_SSL('imap.163.com') mail.login('your_username', 'your_auth_code') # 替换为你的用户名和授权码 # 检查邮箱并选择收件箱 status, mailboxes = mail.list() inbox_idx = mailboxes.index("INBOX") mail.select(inbox_idx) # 搜索未读邮件 typ, data = mail.search(None, "UNSEEN") # 查找所有未读邮件 mail_ids = data[0].split() # 遍历邮件ID,取出邮件内容 for msg_id in mail_ids: typ, raw_message_data = mail.fetch(msg_id, "(RFC822)") # 解析邮件正文 message = email.message_from_bytes(raw_message_data[0][1]) subject, encoding = decode_header(message['Subject'])[0] if isinstance(subject, bytes): subject = subject.decode(encoding) print(f"Subject: {subject}") print(f"From: {message.get('From')}") print("\nMessage Body:\n", message.get_payload()) # 关闭连接 mail.close() mail.logout() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值