I've been trying to work this one out for a while now but keep finding imperfect solutions - I think what I want to do is possible but maybe I'm not phrasing my Google search correctly.
I have a Python script that sends a user an email notification - in order to send said email I need to provide a password in the script to send the email. The code works perfectly but it requires that I pass the password into the script:
def send_email():
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender_email = "my-generic-email#gmail.com"
receiver_email = "recipient#gmail.com"
password = "my_password_here"
message = MIMEMultipart("alternative")
message["Subject"] = "subject_here"
message["From"] = sender_email
message["To"] = receiver_email
# Create the plain-text and HTML version of your message
text = f"""\
Plain text body here
"""
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
I don't want to store the password as plain text for obvious reasons. I've thought of environment variables but this wouldn't work as this is going to be deployed on GitHub for other people to use (or install as an EXE) so this would break the email functionality.
I've tried looking at PyCryptodome but anything I've found so far suggests encrypting the password with a key but then storing the key in the script to decrypt the password when you use it. This seems like a bad idea to me as surely any novice (like me!) would be able to easily decrypt this because the key is stored in the script.
Is anyone able to help push me in the right direction? I'm completely out of ideas as frankly I know hardly anything about password storing/security so not even sure what I should be Googling!
If others have to use your password to be able to use your script, it's impossible. If the computer can read it, then the user will also find a way to read it.
I recommend using a E-Mail service where the user can enter their own API key or just let them enter their own GMail credentials.
Correct me if I'm wrong, but I think there's no way to use your password in this case unless you write an API and send the E-Mail from your server. But don't forget that in this case, the user might be able to use your API as a way to send spam.
TL;DR: Let the users use their own passwords.
Just like many big companies using Office365, my company is using google (gsuite) to host their email domain. I need to send automated emails to multiple people within organisation using a python script. How can that be done?
You can use a 3rd party service like Mailgun, it provides a REST API which if you hit you can trigger emails that it will send from a custom domain you configure on the service.
Its super easy to use for python, I use it for Raspberry Pi projects.
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api", "YOUR_API_KEY"),
data={"from": "Excited User <mailgun#YOUR_DOMAIN_NAME>",
"to": ["bar#example.com", "YOU#YOUR_DOMAIN_NAME"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
It is a nice alternative to using a corporate SMTP server.
Got it fixed.
In order to send an email from Python, we first need to switch ON "Less secure app access" https://myaccount.google.com/lesssecureapps?utm_source=google-account&utm_medium=web.
This we need to do if we don't have 2 Factor Authentication.
If you use 2 Factor Authentication, then you need to create an App Password and use that particular password while sending an email and not your regular password.
To create an App Password use this link: https://support.google.com/mail/answer/185833?hl=en
Now using sample script like below, we can send an email.
import smtplib
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login("username#domain.com", "app_password")
# message to be sent
message = "Message_you_need_to_send"
# sending the mail
s.sendmail("username#domain.com", "recipient#domain.com", message)
# terminating the session
s.quit()
Google provides Gmail api suite for python and it is the preferred way to access versus smtp login/password
You should refer to their developer console for examples and tutorials
I am trying to send an email from a custom domain in Python. I have figured out how to send emails from other domains, like gmail.com, using smtplib [example code]. Now I want to figure out how to send an email from a custom domain like catsareonwheels.com.
I thought I would be able to use smtpd to send emails from a server, but that library appears only to serve as a proxy fora Mail Transfer Agent. From what I can tell, there are MTA's written in Pure Python [e.g. Slimta], but I have not been able to find any examples of snippets that actually demonstrate how to send an email from a custom domain with Python.
If anyone can help point me toward literature that might help me determine how best to achieve this goal, I'd be very grateful.
TO SEND AN EMAIL FROM A CUSTOM DOMAIN, YOU DO THE FOLLOWING:
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
msg = MIMEMultipart()
msg["From"] = "<your_mail_account>"
msg["To"] = "<destiny_account>"
body_text = "HOLA MUNDO :)"
body_part = MIMEText(body_text, 'plain')
msg.attach(body_part)
with smtplib.SMTP(host="smtp.<CUSTOM_DOMAIN>.com", port=587) as smtp_obj: # ENVIAR DESDE UN DOMINIO PERSONALIZADO.
smtp_obj.ehlo()
smtp_obj.starttls()
smtp_obj.ehlo()
smtp_obj.login("<your_mail_account>", "<your_password>")
smtp_obj.sendmail(msg['From'], [msg['To'],], msg.as_string())
print("¡Datos enviados con éxito!")
That's all :) Hope you like it!
After trying all the SMTP server settings that I have found on other posts I have found the right settings browsing through domain cPanel:
Go to "List Email Accounts"
On the right sido of the account you want to use click on "Connect devices"
Check "Mail Client Manual Settings"
What do you exactly mean by "custom domain"?
If you have some hosting witch provides you an email service then you can use smtplib as well.
Lets say I bought a hosting and a domain use-smtplib.com. I've created an email account myname#use-smtplib.com in admin panel.
Then configuration should look somehow like this:
with smtplib.SMTP_SSL('mail.use-smtplib.com', '465') as smtp:
smtp.login('myname#use-smtplib.com', 'my_strong_password')
subject = "Message from python"
msg = "Hello from python"
smtp.sendmail('myname#use-smtplib.com', 'recipient#gmail.com', msg)
Exact configuration may be different depending on your email provider. Domains starting with mail.domain.com and smtp.domain.com are pretty common.
I want to write my own small mailserver application in python with aiosmtpd
a) for educational purpose to better understand mailservers
b) to realize my own features
So my question is, what is missing (besides aiosmtpd) for an Mail-Transfer-Agent, that can send and receive emails to/from other full MTAs (gmail.com, yahoo.com ...)?
I'm guessing:
1.) Of course a domain and static ip
2.) Valid certificate for this domain
...should be doable with Lets Encrypt
3.) Encryption
...should be doable with SSL/Context/Starttls... with aiosmtpd itself
4.) Resolving MX DNS entries for outgoing emails!?
...should be doable with python library dnspython
5.) Error handling for SMTP communication errors, error replies from other MTAs, bouncing!?
6.) Queue for handling inbound and pending outbund emails!?
Are there any other "essential" features missing?
Of course i know, there are a lot more "advanced" features for a mailserver like spam checking, malware checking, certificate validation, blacklisting, rules, mailboxes and more...
Thanks for all hints!
EDIT:
Let me clarify what is in my mind:
I want to write a mailserver for a club. Its main purpose will be a mailing-list-server. There will be different lists for different groups of the club.
Lets say my domain is myclub.org then there will be for example youth#myclub.org, trainer#myclub.org and so on.
Only members will be allowed to use this mailserver and only the members will receive emails from this mailserver. No one else will be allowed to send emails to this mailserver nor will receive emails from it. The members email-addresses and their group(s) are stored in a database.
In the future i want to integrate some other useful features, for example:
Auto-reminders
A chatbot, where members can control services and request informations by email
What i don't need:
User Mailboxes
POP/IMAP access
Webinterface
Open relay issue:
I want to reject any [FROM] email address that is not in the members database during SMTP negotiation.
I want to check the sending mailservers for a valid certificate.
The number of emails/member/day will be limited.
I'm not sure, if i really need spam detection for the incoming emails?
Losing emails issue:
I think i will need a "lightweight" retry mechanism. However if an outgoing email can't be delivered after some retries, it will be dropped and only the administrator will be notified, not the sender. The members should not be bothered by email delivery issues. Is there any Python Library that can generate RFC3464 compliant error reply emails?
Reboot issue:
I'm not sure if i really need persistent storage for emails, that are not yet sent? In my use case, all the outgoing emails should be delivered usually within a few seconds (if no delivery problem occurs). Before a (planned) reboot i can check for an empty send queue.
aiosmtpd is an excellent tool for writing custom routing and header rewriting rules for email. However, aiosmtpd is not an MTA, since it does not do message queuing or DSN generation. One popular choice of MTA is postfix, and since postfix can be configured to relay all emails for a domain to another local SMTP server (such as aiosmtpd), a natural choice is to use postfix as the internet-facing frontend and aiosmtpd as the business-logic backend.
Advantages of using postfix as the middle-man instead of letting aiosmtpd face the public internet:
No need to handle DNS MX lookups in aiosmtpd -- just relay through postfix (localhost:25)
No worry about non-compliant SMTP clients in aiosmtpd
No worry about STARTTLS in aiosmtpd -- configure this in postfix instead (simpler and more battle-hardened)
No worry about retrying failed email deliveries and sending delivery status notifications
aiosmtpd can be configured to respond with "transient failure" (SMTP 4xx code) upon programming errors, so no email is lost as long as the programming error is fixed within 4 days
Here's how you might configure postfix to work with a local SMTP server powered by e.g. aiosmtpd.
We're going to run postfix on port 25 and aiosmtpd on port 20381.
To specify that postfix should relay emails for example.com to an SMTP server running on port 20381, add the following to /etc/postfix/main.cf:
transport_maps = hash:/etc/postfix/smtp_transport
relay_domains = example.com
And create /etc/postfix/smtp_transport with the contents:
# Table of special transport method for domains in
# virtual_mailbox_domains. See postmap(5), virtual(5) and
# transport(5).
#
# Remember to run
# postmap /etc/postfix/smtp_transport
# and update relay_domains in main.cf after changing this file!
example.com smtp:127.0.0.1:20381
Run postmap /etc/postfix/smtp_transport after creating that file (and every time you modify it).
On the aiosmtpd side, there are a few things to consider.
The most important is how you handle bounce emails. The short story is that you should set the envelope sender to an email address you control that is dedicated to receiving bounces, e.g. bounce#example.com. When email arrives at this address, it should be stored somewhere so you can process bounces, e.g. by removing member email addresses from your database.
Another important thing to consider is how you tell your members' email providers that you are doing mailing list forwarding. You might want to add the following headers when forwarding emails to GROUP#example.com:
Sender: bounce#example.com
List-Name: GROUP
List-Id: GROUP.example.com
List-Unsubscribe: <mailto:postmaster#example.com?subject=unsubscribe%20GROUP>
List-Help: <mailto:postmaster#example.com?subject=list-help>
List-Subscribe: <mailto:postmaster#example.com?subject=subscribe%20GROUP>
Precedence: bulk
X-Auto-Response-Suppress: OOF
Here, I used postmaster#example.com as the recipient for list unsubscribe requests. This should be an address that forwards to the email administrator (that is, you).
Below is a skeleton (untested) that does the above. It stores bounce emails in a directory named bounces and forwards emails with a valid From:-header (one that appears in MEMBERS) according to the list of groups (in GROUPS).
import os
import email
import email.utils
import mailbox
import smtplib
import aiosmtpd.controller
LISTEN_HOST = '127.0.0.1'
LISTEN_PORT = 20381
DOMAIN = 'example.com'
BOUNCE_ADDRESS = 'bounce'
POSTMASTER = 'postmaster'
BOUNCE_DIRECTORY = os.path.join(
os.path.dirname(__file__), 'bounces')
def get_extra_headers(list_name, is_group=True, skip=()):
list_id = '%s.%s' % (list_name, DOMAIN)
bounce = '%s#%s' % (BOUNCE_ADDRESS, DOMAIN)
postmaster = '%s#%s' % (POSTMASTER, DOMAIN)
unsub = '<mailto:%s?subject=unsubscribe%%20%s>' % (postmaster, list_name)
help = '<mailto:%s?subject=list-help>' % (postmaster,)
sub = '<mailto:%s?subject=subscribe%%20%s>' % (postmaster, list_name)
headers = [
('Sender', bounce),
('List-Name', list_name),
('List-Id', list_id),
('List-Unsubscribe', unsub),
('List-Help', help),
('List-Subscribe', sub),
]
if is_group:
headers.extend([
('Precedence', 'bulk'),
('X-Auto-Response-Suppress', 'OOF'),
])
headers = [(k, v) for k, v in headers if k.lower() not in skip]
return headers
def store_bounce_message(message):
mbox = mailbox.Maildir(BOUNCE_DIRECTORY)
mbox.add(message)
MEMBERS = ['foo#example.net', 'bar#example.org',
'clubadmin#example.org']
GROUPS = {
'group1': ['foo#example.net', 'bar#example.org'],
POSTMASTER: ['clubadmin#example.org'],
}
class ClubHandler:
def validate_sender(self, message):
from_ = message.get('From')
if not from_:
return False
realname, address = email.utils.parseaddr(from_)
if address not in MEMBERS:
return False
return True
def translate_recipient(self, local_part):
try:
return GROUPS[local_part]
except KeyError:
return None
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
local, domain = address.split('#')
if domain.lower() != DOMAIN:
return '550 wrong domain'
if local.lower() == BOUNCE:
envelope.is_bounce = True
return '250 OK'
translated = self.translate_recipient(local.lower())
if translated is None:
return '550 no such user'
envelope.rcpt_tos.extend(translated)
return '250 OK'
async def handle_DATA(self, server, session, envelope):
if getattr(envelope, 'is_bounce', False):
if len(envelope.rcpt_tos) > 0:
return '500 Cannot send bounce message to multiple recipients'
store_bounce_message(envelope.original_content)
return '250 OK'
message = email.message_from_bytes(envelope.original_content)
if not self.validate_sender(message):
return '500 I do not know you'
for header_key, header_value in get_extra_headers('club'):
message[header_key] = header_value
bounce = '%s#%s' % (BOUNCE_ADDRESS, DOMAIN)
with smtplib.SMTP('localhost', 25) as smtp:
smtp.sendmail(bounce, envelope.rcpt_tos, message.as_bytes())
return '250 OK'
if __name__ == '__main__':
controller = aiosmtpd.controller.Controller(ClubHandler, hostname=LISTEN_HOST, port=LISTEN_PORT)
controller.start()
print("Controller started")
try:
while True:
input()
except (EOFError, KeyboardInterrupt):
controller.stop()
The most important thing about running your own SMTP server is that you must not be an open relay. That means you must not accept messages from strangers and relay them to any destination on the internet, since that would enable spammers to send spam through your SMTP server -- which would quickly get you blocked.
Thus, your server should
relay from authenticated users/senders to remote destinations, or
relay from strangers to your own domains.
Since your question talks about resolving MX records for outgoing email, I'm assuming you want your server to accept emails from authenticated users. Thus you need to consider how your users will authenticate themselves to the server. aiosmtpd currently has an open pull request providing a basic SMTP AUTH implementation; you may use that, or you may implement your own (by subclassing aiosmtpd.smtp.SMTP and implementing the smtp_AUTH() method).
The second-most important thing about running your own SMTP server is that you must not lose emails without notifying the sender. When you accept an email from an authenticated user to be relayed to an external destination, you should let the user know (by sending an RFC 3464 Delivery Status Notification via email) if the message is delayed or if it is not delivered at all.
You should not drop the email immediately if the remote destination fails to receive it; you should try again later and repeatedly try until you deem that you have tried for long enough. Postfix, for instance, waits 10 minutes before trying to deliver the email after the first delivery attempt fails, and then it waits 20 minutes if the second attempt fails, and so on until the message has been attempted delivered for a couple days.
You should also take care to allow the host running your mail server to be rebooted, meaning you should store queued messages on disk. For this you might be able to use the mailbox module.
Of course, I haven't covered every little detail, but I think the above two points are the most important, and you didn't seem to cover them in your question.
You may consider the following features:
Message threading
Support for Delivery status
Support for POP and IMAP protocols
Supports for protocols such as RFC 2821 SMTP and RFC 2033 LMTP email message transport
Support Multiple message tagging
Support for PGP/MIME (RFC2015)
Support list-reply
Lets each user manage their own mail lists Supports
Control of message headers during composition
Support for address groups
Prevention of mailing list loops
Junk mail control
I'm trying to write a separate mail service, which is decoupled with our Flask application. I'm looking for a way to send welcome emails when users first log into our Flask application. I'm using Celery and RabbitMQ to do it asynchronously.
Here is my email function:
sen = 'example#gmail.com'
pwd = 'my_password'
#celery.task
def send_email(nickname, email):
msg = MIMEMultipart('alternative')
msg['Subject'] = 'my_sub'
msg['From'] = sen
msg['To'] = email
html = <b>test_body</b>
part1 = MIMEText(html, 'html')
msg.attach(part1)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(sen, pwd)
server.sendmail(sen, [email], msg.as_string())
server.close()
Initially I was using Flask's render_template to get the HTML body and subject. But I don't want to use the Flask extension (I have my reasons). So my questions are:
How can I use email templates so that the subject and body fields can be configured easily?
How can I put the default email sender and password in a config file/email template (might be related to q1)?
It seems to be that I have a lot of code to send a simple email. Can you suggest some optimization techniques (omitting steps)?
I've wrritten a simple module(mail.py) to send emails using templates(HTML/TEXT). Hope that helps!
https://github.com/ludmal/pylib
It may be simpler to use an external service.
A service (e.g. Mailchimp) is simple to integrate. You can design the template in their layer, and trigger emails by sending merge data from your app to the service API. Functionally it's a lot like rendering a template locally and mailing it out via SMTP, but they have sophisticated tools for adapting message format to devices, tracking bounces, improving deliverability, reporting etc.
Services like this often have a free tier for up to 1000's of emails per month.