使用 python smtplib

问题描述

我有一个 python 脚本,用于将邮件发送到邮件 ID 列表。 我现在正在尝试从别名邮件 ID 发送邮件。我已经在 GSuite 中创建了别名邮件。 我现在有以下代码

user = '[email protected]'  # Email userID
password = 'password'  # Email password
from_addr = '[email protected]'
from_name = 'User Name'    
recipients_addr = '[email protected]'
subject = 'This is subject'
body = "this is mail body"
file_path = [file1,file2] 
   
send_email(user,password,from_addr,from_name,recipients_addr,subject,body,file_path)

send_email() 函数

def send_email(user,cc_addr,files_path=None,server='smtp.gmail.com'):
    #   assert isinstance(recipents_addr,list)
    FROM = from_addr
    FROMNAME = from_name
    TO = recipients_addr if isinstance(recipients_addr,list) else recipients_addr.split(' ')
    CC = cc_addr if isinstance(cc_addr,list) else cc_addr.aplit(' ')
    PASS = password
    SERVER = server
    SUBJECT = subject
    BODY = body
    msg = mime_init(FROM,FROMNAME,TO,CC,SUBJECT,BODY)

    for file_path in files_path or []:
        with open(file_path,"rb") as fp:
            part = MIMEBase('application',"octet-stream")
            part.set_payload((fp).read())
            # Encoding payload is necessary if encoded (compressed) file has to be attached.
            encoders.encode_base64(part)
            part.add_header('Content-disposition',"attachment; filename= %s" % os.path.basename(file_path))
            msg.attach(part)

    if SERVER == 'localhost':  # send mail from local server
        # Start local SMTP server
        server = smtplib.SMTP(SERVER)
        text = msg.as_string()
        server.send_message(msg)
    else:
        # Start SMTP server at port 587
        server = smtplib.SMTP(SERVER,587)
        server.starttls()
        # Enter login credentials for the email you want to sent mail from
        server.login(user,PASS)
        text = msg.as_string()
        # Send mail
        server.sendmail(FROM,text)

    server.quit()
    print('Mail Sent!')

mime_init() 函数

def mime_init(from_addr,body):
    msg = MIMEMultipart()

    msg['From'] = formataddr((from_name,from_addr))
    msg['To'] = ','.join(recipients_addr)
    msg['CC'] = ','.join(cc_addr)
    msg['Subject'] = subject
    msg.attach(MIMEText(body,'plain'))
    return msg

我什至尝试将别名邮件作为电子邮件用户 ID 和发件人地址传递,但它不起作用。

我正在尝试从别名邮件 ID 发送邮件。有人可以帮我吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)