Python Gmail密件抄送和抄送

2024-09-26 22:53:28 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我编写了这段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)

Tags: pathimportmessagegetserveremaildeflogin
1条回答
网友
1楼 · 发布于 2024-09-26 22:53:28

你可以试试这个

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()

相关问题 更多 >

    热门问题