# Mail Injection
Many web applications send *transactional emails* in response to user actions. A **mail injection** vulnerability occurs when an attacker can maliciously craft an HTTP request that causes emails to be sent with arbitrary SMTP headers. This vulnerability is often used by spammers to send bulk email from a victim’s server.
## Mail Injection in Python
It’s easy to send email in Python using the `smtplib` module. Consider the following web application that sends email invites with a customizable message:
“`python import smtplib from email.message import EmailMessagedef send_invite_email(request): message = EmailMessage() message.set_content(request.args[‘body’]) smtp = smtplib.SMTP(os.environ.get(‘SMTP_HOST’)) |
This action is wide open to abuse by spammers, since the `To` address, subject line and body are all set from the HTTP request, and can be controlled by an attacker. The email will be sent from your email server, and under your email domain, so it will bypass any sender verification checks put in place by the email client. However, you will quickly find your email domain appearing on spamming blacklists, so legitimate email you send will stop being delivered.
## Mitigation
* Do not construct the `To` addresses, subject line, email body or SMTP headers from untrusted content. Make sure the contents of the email are constructed entirely on the server-side, and try to send transactional email only to users who have signed up to your service (and have verified ownership of their email address).
* Where you are sending emails to a new address – for instance, in the event of sign-ups or invites – make sure the action is triggered by an authenticated user, or requires the user to pass a CAPTCHA test. Throttle the outgoing emails by email address, so you don’t cause a nuisance.
* Validate all email addresses before sending any email – in particular, check for new line characters that may allow an attacker to inject extra headers.
* Consider using a transactional email provider service. Not only will this allow you to track how many emails you send, you can track any that fail to get delivered and bounce back.