如何通过Gmail发送包含多个抄送的邮件

1 投票
2 回答
5962 浏览
提问于 2025-04-16 13:41

我想找一个简单的例子,教我怎么用Gmail发送邮件,并且可以抄送给多个收件人。有没有人能给我提供一个示例代码?

2 个回答

1

如果你可以使用一个库,我强烈推荐 http://libgmail.sourceforge.net/,我之前简单用过,使用起来非常方便。你需要在你的 Gmail 账户中开启 IMAP/POP3 功能才能使用这个库。

关于代码片段(我还没机会试过这个,如果有机会我会更新的):

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os

#EDIT THE NEXT TWO LINES
gmail_user = "your_email@gmail.com"
gmail_pwd = "your_password"

def mail(to, subject, text, attach, cc):
   msg = MIMEMultipart()

   msg['From'] = gmail_user
   msg['To'] = to
   msg['Subject'] = subject

   #THIS IS WHERE YOU PUT IN THE CC EMAILS
   msg['Cc'] = cc
   msg.attach(MIMEText(text))

   part = MIMEBase('application', 'octet-stream')
   part.set_payload(open(attach, 'rb').read())
   Encoders.encode_base64(part)
   part.add_header('Content-Disposition',
           'attachment; filename="%s"' % os.path.basename(attach))
   msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

mail("some.person@some.address.com",
   "Hello from python!",
   "This is a email sent with python")

对于这个代码片段,我修改了 这个

1

我给你准备了一段代码,展示了如何连接到一个SMTP服务器,构建一封电子邮件(在抄送字段中添加几个地址),并发送它。希望代码中加了很多注释,能让你更容易理解。

from smtplib import SMTP_SSL
from email.mime.text import MIMEText

## The SMTP server details

smtp_server = "smtp.gmail.com"
smtp_port = 587
smtp_username = "username"
smtp_password = "password"

## The email details

from_address = "address1@domain.com"
to_address = "address2@domain.com"

cc_addresses = ["address3@domain.com", "address4@domain.com"]

msg_subject = "This is the subject of the email"

msg_body = """
This is some text for the email body.
"""

## Now we make the email

msg = MIMEText(msg_body) # Create a Message object with the body text

# Now add the headers
msg['Subject'] = msg_subject
msg['From'] = from_address
msg['To'] = to_address
msg['Cc'] = ', '.join(cc_addresses) # Comma separate multiple addresses

## Now we can connect to the server and send the email

s = SMTP_SSL(smtp_server, smtp_port) # Set up the connection to the SMTP server
try:
    s.set_debuglevel(True) # It's nice to see what's going on

    s.ehlo() # identify ourselves, prompting server for supported features

    # If we can encrypt this session, do it
    if s.has_extn('STARTTLS'):
        s.starttls()
        s.ehlo() # re-identify ourselves over TLS connection

    s.login(smtp_username, smtp_password) # Login

    # Send the email. Note we have to give sendmail() the message as a string
    # rather than a message object, so we need to do msg.as_string()
    s.sendmail(from_address, to_address, msg.as_string())

finally:
    s.quit() # Close the connection

这里是上面代码在pastie.org上的链接,方便你阅读

关于多个抄送地址的问题,正如你在上面的代码中看到的,你需要使用一个用逗号分隔的字符串来写电子邮件地址,而不是用列表。

如果你想同时显示名字和地址,可以使用email.utils.formataddr()函数来帮助你把它们格式化成正确的样子:

>>> from email.utils import formataddr
>>> addresses = [("John Doe", "john@domain.com"), ("Jane Doe", "jane@domain.com")]
>>> ', '.join([formataddr(address) for address in addresses])
'John Doe <john@domain.com>, Jane Doe <jane@domain.com>'

希望这对你有帮助,如果你有任何问题,随时告诉我。

撰写回答