用Python实现邮件发送

邮件发送程序代码:

  
  
import smtplib  
from email.mime.text import MIMEText  
from email.mime.multipart import MIMEMultipart  
from email.mime.base import MIMEBase  
from email import encoders  
import os  
from email.header import Header  
  
class EmailSender:  
    def __init__(self, sender_email, sender_password, smtp_server, smtp_port, sender_name=None):  
        self.sender_email = sender_email  
        self.sender_password = sender_password  
        self.smtp_server = smtp_server  
        self.smtp_port = smtp_port  
        self.sender_name = sender_name  # 添加这一行  
  
    def send_email(self, receiver_email, subject, message, attachment_path=None, smtp_port=None):  
        msg = MIMEMultipart()  
        sender_header = Header(self.sender_name, 'utf-8') if self.sender_name else self.sender_email  
        msg['From'] = sender_header  
        msg['To'] = receiver_email  
        msg['Subject'] = subject  
  
        msg.attach(MIMEText(message, 'plain'))  
  
        if attachment_path and os.path.exists(attachment_path):  
            attachment = open(attachment_path, 'rb')  
            part = MIMEBase('application', 'octet-stream')  
            part.set_payload(attachment.read())  
            encoders.encode_base64(part)  
            part.add_header('Content-Disposition', f'attachment; filename= {os.path.basename(attachment_path)}')  
            msg.attach(part)  
  
        try:  
            with smtplib.SMTP(self.smtp_server, self.smtp_port if not smtp_port else smtp_port) as server:  
                server.starttls()  
                server.login(self.sender_email, self.sender_password)  
                server.sendmail(self.sender_email, receiver_email, msg.as_string())  
                print("邮件发送成功!")  
        except smtplib.SMTPException as e:  
            print(f"发送邮件时出现错误:{e}")  
  
# 测试调用  
def main():  
    sender_email = '你的邮箱地址'  # 发送者邮箱  
    sender_password = '你的邮箱密码'  # smtp密码或者自建邮箱的邮箱密码  
    smtp_server = 'smtp.example.com'  # 邮箱服务器地址  
    smtp_port = 587  # 根据你的邮箱服务商选择合适的端口,例如Gmail是587,QQ邮箱是465(SSL)或587(STARTTLS)  
    sender_name = '你的名字'  # 可选,发件人名字  
  
    email_sender = EmailSender(sender_email, sender_password, smtp_server, smtp_port, sender_name=sender_name)  
    email_sender.send_email('接收者邮箱地址', '邮件主题', '邮件内容', attachment_path='/path/to/attachment.txt')  
  
if __name__ == '__main__':  
    main().

你需要将sender_email, sender_password, smtp_server, smtp_port和sender_name替换为实际的值。
你需要将receiver_email和attachment_path替换为实际的接收者邮箱地址和附件路径(如果你想添加附件的话)。
根据你的邮箱服务商,smtp_port可能需要更改。例如,Gmail使用587端口,而QQ邮箱可以使用465(SSL)或587(STARTTLS)端口。
某些邮箱服务商可能需要你在账户设置中开启“不够安全的应用”的访问权限,或者使用应用专用密码(而非你的邮箱密码)作为sender_password。
在真实环境中,不建议在代码中硬编码敏感信息(如邮箱密码),而应使用

smtplib模块MIMEText 模块MIMEMultipart 模块MIMEBase模块encoders模块os模块Header模块邮件发送

我来吐槽

*

*