Send email
Send email
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
- If appropriate, explain what notifications of problems/success are given.
- Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
- Note how portable the solution given is between operating systems when multi-OS languages are used.
(Remember to obfuscate any sensitive data used in examples)
Python
The function returns a dict of any addresses it could not forward to; other connections problems raise errors.
Tested on Windows, it should work on POSIX platforms too.
<lang python>import smtplib
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message, login, password, smtpserver='smtp.gmail.com:587'): header = 'From: %s\n' % from_addr header += 'To: %s\n' % ','.join(to_addr_list) header += 'Cc: %s\n' % ','.join(cc_addr_list) header += 'Subject: %s\n\n' % subject message = header + message server = smtplib.SMTP(smtpserver) server.starttls() server.login(login,password) problems = server.sendmail(from_addr, to_addr_list, message) server.quit() return problems</lang>
Example use: <lang python>sendemail(from_addr = 'python@RC.net',
to_addr_list = ['RC@gmail.com'], cc_addr_list = ['RC@xx.co.uk'], subject = 'Howdy', message = 'Howdy from a python function', login = 'pythonuser', password = 'XXXXX')
</lang>
Sample Email received:
Message-ID: <4a4a1e78.0717d00a.1ba8.ffcfdbdd@xx.google.com> Date: Tue, 30 Jun 2009 22:04:56 -0700 (PDT) From: python@RC.net To: RC@gmail.com Cc: RC@xx.co.uk Subject: Howdy Howdy from python function