所以,我制作了使用 Gmail 帐户发送电子邮件的 Python 代码,但我不知道如何添加 CC 和 密件抄送 >.有人可以帮我吗?
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)
答案 0 :(得分:0)
你可以试试这个
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()