Created
January 3, 2021 20:15
-
-
Save tanimislam/8bdbf28f9fbd2d040c555f4ec26fdc8d to your computer and use it in GitHub Desktop.
testing email functionality using sender and recipient with user-defined port number
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
#!/usr/bin/env python3 | |
import os, sys, numpy, smtplib, logging, datetime | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from argparse import ArgumentParser | |
def test_simple_email( recipient, sender, port_number ): | |
""" | |
send a simple test email from ``recipient`` to ``sender``, at ``port_number`` on the local machine, using the SMTP_ protocol. | |
:param str recipient: the `RFC 2047`_ recipient's email with name. | |
:param str sender: the `RFC 2047`_ sender's email with name. | |
:param int port_number: a valid (:math:`1 \le`\ ``port_number`` :math:`\le 65535`) port number on the local machine. | |
.. _`RFC 2047`: https://tools.ietf.org/html/rfc2047.html | |
""" | |
assert( port_number > 0 ) | |
assert( port_number < 65536 ) | |
# | |
## first create the MIMEMultipart message | |
email_text = '\n'.join(['This is a test email.', 'I hope it works!' ]) | |
msg = MIMEMultipart( ) | |
msg[ 'To' ] = recipient | |
msg[ 'From' ] = sender | |
msg[ 'Subject'] = 'test email from %s to %s @ %s.' % ( sender, recipient, datetime.datetime.now( ).date( ).strftime( '%d %B %Y' ) ) | |
msg.attach( MIMEText( email_text, 'plain', 'utf-8' ) ) | |
# | |
## now send it out! | |
smtp_conn = smtplib.SMTP('localhost', port_number ) | |
smtp_conn.ehlo( 'test' ) | |
smtp_conn.sendmail( msg['From'], [ msg["To"], ], msg.as_string( ) ) | |
smtp_conn.quit( ) | |
if __name__=='__main__': | |
# | |
## usage case is simple: test_email.py -R "name <email>" -S from argparse import ArgumentParser"name <email>" -P <port_number> | |
parser = ArgumentParser( ) | |
parser.add_argument( '-R', '--recipient', dest='recipient', type=str, required = True, | |
help = 'The RFC 2047 (name <email>) form of the recipient.' ) | |
parser.add_argument( '-S', '--sender', dest='sender', type=str, required = True, | |
help = 'The RFC 2047 (name <email>) form of the sender.' ) | |
parser.add_argument( '-P', dest='port_number', type=int, default = 25, | |
help = 'The port number on location machine to test email sending functionality. Default is port 25.' ) | |
parser.add_argument( '--info', dest='do_info', action='store_true', default = False, | |
help = 'If chosen, then run with INFO logging.' ) | |
# | |
args = parser.parse_args( ) | |
logger = logging.getLogger( ) | |
if args.do_info: logger.setLevel( logging.INFO ) | |
test_simple_email( args.recipient, args.sender, args.port_number ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment