Search code examples
pythonemail-headers

How to send Gmail email with multiple CC:'s


I am looking for a quick example on how to send Gmail emails with multiple CC:'s. Could anyone suggest an example snippet?


Solution

  • I've rustled up a bit of code for you that shows how to connect to an SMTP server, construct an email (with a couple of addresses in the Cc field), and send it. Hopefully the liberal application of comments will make it easy to understand.

    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
    

    Here's the code above on pastie.org for easier reading

    Regarding the specific question of multiple Cc addresses, as you can see in the code above, you need to use a comma separated string of email addresses, rather than a list.

    If you want names as well as addresses you might as well use the email.utils.formataddr() function to help get them into the right format:

    >>> 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>'
    

    Hope this helps, let me know if you have any problems.