Skip to content

Instantly share code, notes, and snippets.

@dp7k
Created October 30, 2015 19:37
Show Gist options
  • Select an option

  • Save dp7k/46efbb2e39940e68134e to your computer and use it in GitHub Desktop.

Select an option

Save dp7k/46efbb2e39940e68134e to your computer and use it in GitHub Desktop.
simple mail function
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from smtplib import SMTP
from email.utils import formatdate
import socket # catch socket.error
def send_mail(recipent, sender, subject, body, server_addr='127.0.0.1', server_port=25):
"""
Send a simple email
:param recipent: recipent email address ``'[email protected]'`` with optional display name ``'Foo Bar <[email protected]>'``
:param sender: sender email address ``'[email protected]'`` with optional display name ``'Foo Bar <[email protected]>'``
:param subject: mail subject
:param body: mail body / message
:param server_addr: mail server address, default: ``127.0.0.1``
:param server_port: mail server port, default: ``25``
:type recipent: str
:type sender: str
:type subject: str
:type body: str
:type server_addr: str
:type server_port: int
:return: success
:rtype: bool
"""
header = "From: <%s>\n" % (sender)
header += "To: <%s>\n" % (recipent)
header += "Subject: %s\n" % (subject)
header += "Date: %s\n" % (formatdate())
header += "Content-Type: text/plain; charset=UTF-8\n"
message = header + '\n' + body
# SMTP
try:
smtp = SMTP(server_addr, server_port)
smtp.sendmail(sender, recipent, message.encode('utf-8'))
success = True
except socket.error:
success = False
return success
if __name__ == "__main__":
print(send_mail('[email protected]', '[email protected]', 'My subject', 'Hello from python!'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment