Created
July 15, 2017 16:32
-
-
Save akshaykarnawat/c69b9670dfb155823c18101e8563cd4e to your computer and use it in GitHub Desktop.
Python email sender
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
''' | |
Email Sender | |
''' | |
import smtplib | |
import traceback | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
def send_mail(smtp_user, smtp_password, mail_to, subject, message, smtp_host, smtp_port): | |
''' | |
Send an email based on the parameters passed | |
Args: | |
smtp_user (string): the email address of the sender. Also used to login into the | |
mail server. | |
smtp_password (string): the email password of the sender. Only used to login into | |
the mail server. | |
mail_to (string): the receiver's email address | |
subject (string): the subject of the message | |
message (string): the message to send to the user | |
smtp_host (string): the email providers smtp host | |
smtp_port (int): the email providers smtp port | |
''' | |
msg = MIMEMultipart('alternative') | |
msg['Subject'] = subject | |
msg['From'] = smtp_user | |
msg['To'] = mail_to | |
html = """ | |
<html> | |
<head></head> | |
<body> | |
<p>Good Day Receiver,</p> | |
<p>Sending emails this way has never been this fun :P</p> | |
<p>{0}</p> | |
<br> | |
<p>Cheers,<br> | |
<br> | |
Mammal from Earth<br> | |
</p> | |
</body> | |
</html> | |
""".format(message) | |
html_message = MIMEText(html, 'html') | |
msg.attach(html_message) | |
try: | |
smtp_server = smtplib.SMTP(host=smtp_host, port=smtp_port) | |
smtp_server.ehlo() | |
smtp_server.starttls() | |
smtp_server.login(user=smtp_user, password=smtp_password) | |
smtp_server.sendmail(from_addr=smtp_user, to_addrs=mail_to, msg=msg.as_string()) | |
smtp_server.close() | |
except smtplib.SMTPException: | |
print(traceback.format_exc()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment