首页 > 解决方案 > Python Gmail 密件抄送和抄送

问题描述

所以,我制作了这个Python 代码,它使用 gmail 帐户发送电子邮件,但我不知道如何添加CCBCC。有人能帮我吗?

import smtplib
from email.message import EmailMessage

def get_cred(PATH):
    with open(PATH, "r") as f:
        file = f.readlines();
        login = file[0]
        password = file[1]
    return login, password

def sendemail(message):
    login, password = get_cred("c:\\mypath")
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(login, password)
    server.send_message(message)
    server.quit()

sender = get_cred("c:\\mypath")
message = EmailMessage()
message['Subject'] = 'test'
message['From'] = sender
message['To'] = 'reciever_email@gmail.com'
message.set_content("test")
sendemail(message)

标签: pythonemail

解决方案


你可以试试这个

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

toaddr = ['foo@bar.us','jhon@doe.it']
cc = ['aaa@bb.com','cc@dd.com']
bcc = ['hello@world.uk']

subject = 'Email from Python Code'
fromaddr = 'your@email.com'
message = "\n  !! Hello... !!"

msg            = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From']    = fromaddr 
msg['To']      = ', '.join(toaddr)
msg['Cc']      = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)

# Create the body of the message (an HTML version).
text = """Hi  this is the body
"""

# Record the MIME types of both parts - text/plain and text/html.
body = MIMEText(text, 'plain')

# Attach parts into message container.
msg.attach(body)

# Send the message via local SMTP server.
s = smtplib.SMTP('server.com', 587)
s.set_debuglevel(1)
s.ehlo()
s.starttls()
s.login(fromaddr, PASSWORD)
s.sendmail(fromaddr, toaddr, msg.as_string())
s.quit()

推荐阅读