Created
July 7, 2020 17:22
-
-
Save markdouthwaite/05a4f7a2fa3c059205fc26c18fb2a28b to your computer and use it in GitHub Desktop.
Send an email using GMail to one or more recipients.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
MIT License | |
Copyright (c) 2018-2020 Mark Douthwaite | |
Send Email Snippet | |
------------------ | |
Send an email from a given account to a target set of recipients. | |
If you're using GMail (as the example is configured for by default), you'll need to | |
make sure you've set your 'sender' account to enable 'Less secure app access'. You | |
can do this by going to your GMail account settings > Accounts and Import, click | |
'Other Google Account Settings', head to 'Security', find the 'Less secure app access' | |
section and toggle it on. You should now be able to send emails. | |
""" | |
import os | |
import smtplib | |
from typing import List, Optional, Any | |
from email.message import EmailMessage | |
def prepare_message( | |
sender: str, receivers: List[str], subject: str, content: str | |
) -> EmailMessage: | |
"""Create a new EmailMessage and prepare it to be sent.""" | |
message = EmailMessage() | |
message.set_content(content) | |
message["subject"] = subject | |
message["from"] = sender | |
message["to"] = ", ".join(receivers) | |
return message | |
def send( | |
sender: str, | |
receivers: List[str], | |
password: str = os.getenv("PASSWORD"), | |
host: str = "smtp.gmail.com", | |
port: int = 465, | |
**kwargs: Optional[Any], | |
) -> None: | |
"""Send a message from 'sender' to provided 'receivers'.""" | |
with smtplib.SMTP_SSL(host, port=port) as server: | |
server.login(sender, password) | |
message = prepare_message(sender, receivers, **kwargs) | |
server.send_message(message) | |
# set up your senders and receivers. | |
FROM: str = "you.account@gmail.com" | |
TO: List[str] = ["jane.smith@gmail.com", "john.appleseed@gmail.com"] | |
# send a simple string. | |
send(FROM, TO, subject="Test Email", content="Hello, world!") | |
# send from file | |
with open("newsletter.html", "r") as newsletter: | |
send(FROM, TO, subject="My Newsletter", content=newsletter.read()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment