Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Used context manager for SMTP connection #77

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions massmail
Original file line number Diff line number Diff line change
Expand Up @@ -260,13 +260,6 @@ def add_email_headers(options, msgs):
return None

def send_messages(options, msgs):
if not options['fake']:
server = smtplib.SMTP(options['server'], port=options['port'])

if options['smtpuser'] is not None and not options['fake']:
server.starttls()
server.login(options['smtpuser'], options['smtppassword'])

for emailaddr in msgs:
print('Sending email to:', emailaddr)
emails = [e.strip() for e in emailaddr.split(',')]
Expand All @@ -276,16 +269,19 @@ def send_messages(options, msgs):
print(msgs[emailaddr].as_string())
else:
try:
out = server.sendmail(options['from'], emails, msgs[emailaddr].as_string())
with smtplib.SMTP(options['server'], port=options['port']) as smtp_server:
if options['smtpuser'] is not None:
smtp_server.starttls()
smtp_server.login(options['smtpuser'], options['smtppassword'])

out = smtp_server.sendmail(options['from'], emails, msgs[emailaddr].as_string())

except Exception as err:
error(str(err))

if len(out) != 0:
error(str(out))

if not options['fake']:
server.close()

def main(arguments):
options = parse_command_line_options(arguments)
keywords, email_count = parse_parameter_file(options)
Expand Down