3 import configparser as _configparser
4 import smtplib as _smtplib
6 from . import LOG as _LOG
9 SENDMAIL = ['/usr/sbin/sendmail', '-t']
12 def get_smtp_params(config):
13 r"""Retrieve SMTP paramters from a config file.
15 >>> from configparser import ConfigParser
16 >>> config = ConfigParser()
17 >>> config.read_string('\n'.join([
19 ... 'host: smtp.mail.uu.edu',
22 ... 'username: rincewind',
23 ... 'password: 7ugg@g3',
25 >>> get_smtp_params(config)
26 ('smtp.mail.uu.edu', 587, True, 'rincewind', '7ugg@g3')
27 >>> config = ConfigParser()
28 >>> get_smtp_params(ConfigParser())
29 (None, None, None, None, None)
32 host = config.get('smtp', 'host')
33 except _configparser.NoSectionError:
34 return (None, None, None, None, None)
35 except _configparser.NoOptionError:
38 port = config.getint('smtp', 'port')
39 except _configparser.NoOptionError:
42 starttls = config.getboolean('smtp', 'starttls')
43 except _configparser.NoOptionError:
46 username = config.get('smtp', 'username')
47 except _configparser.NoOptionError:
50 password = config.get('smtp', 'password')
51 except _configparser.NoOptionError:
53 return (host, port, starttls, username, password)
55 def get_smtp(host=None, port=None, starttls=None, username=None,
57 """Connect to an SMTP host using the given parameters.
60 >>> try: # doctest: +SKIP
61 ... smtp = get_smtp(host='smtp.gmail.com', port=587, starttls=True,
62 ... username='rincewind@uu.edu', password='7ugg@g3')
63 ... except smtplib.SMTPAuthenticationError as error:
64 ... print('that was not a real account')
65 that was not a real account
66 >>> smtp = get_smtp() # doctest: +SKIP
67 >>> smtp.quit() # doctest: +SKIP
72 port = _smtplib.SMTP_PORT
73 if username and not starttls:
75 'sending passwords in the clear is unsafe! Use STARTTLS.')
76 _LOG.info('connect to SMTP server at {}:{}'.format(host, port))
77 smtp = _smtplib.SMTP(host=host, port=port)
82 smtp.login(username, password)
83 #smtp.set_debuglevel(1)
86 def mail(message, smtp=None, sendmail=None):
87 """Send an email ``Message`` instance on its merry way.
89 We can shell out to the user specified sendmail in case
90 the local host doesn't have an SMTP server set up
91 for easy ``smtplib`` usage.
93 >>> from pgp_mime.email import encodedMIMEText
94 >>> message = encodedMIMEText('howdy!')
95 >>> message['From'] = 'John Doe <jdoe@a.gov.ru>'
96 >>> message['To'] = 'Jack <jack@hill.org>, Jill <jill@hill.org>'
97 >>> mail(message=message, sendmail=SENDMAIL) # doctest: +SKIP
99 _LOG.info('send message {} -> {}'.format(message['from'], message['to']))
101 smtp.send_message(msg=message)
104 sendmail, stdin=message.as_string().encode('us-ascii'),
107 smtp = _smtplib.SMTP()
109 smtp.send_message(msg=message)