How does one send an e-mail from python NOT using

2020-06-06 02:15发布

问题:

I already have code for sending e-mails with python:

def send_email_gmail(subject, message, destination):
    """ Send an e-mail using gmail with message to destination email.

    Arguments:
        message {str} -- message string to send.
        destination {str} -- destination email (as string)
    """
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    # not a real email account nor password, its all ok!
    server.login('me123@gmail.com', 'fakepassword111!!!')

    # craft message
    msg = EmailMessage()

    message = f'{message}\n'
    msg.set_content(message)
    msg['Subject'] = subject
    msg['From'] = 'me123@gmail.com'
    msg['To'] = destination
    # send msg
    server.send_message(msg)

and I've read the multiple question (Login credentials not working with Gmail SMTP or SMTPAuthenticationError when sending mail using gmail and python) solving the common error:

smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sadfdgjsfgrp=1&dsfgscc=1dsdfgsfg&pldsfgt=AKsdfsdfggsdfggnsbu\n5.7.14 G0crCr0qSvWTng9xRE_pd3WnK3S2sDMsdfgsdfgX0J-xoetn7aHyFQi2qYrQisdfgsdfgKIwMCcgD7zLB1t7Z\n5.7.14 -OjHjpJqasdftBuTi9wh0sYlNW637SmPLuMnnLGn_WcZX5TGH4sddsfgXYar-Aasdfw0ctWfLhasdffPQV>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14  Learn more at\n5.7.14  https://support.google.com/mail/answer/787521345364524 n21sm17577sadfdsf46qtn.17 - gsmtp')

Anyway, I did what those answers suggest but I am still getting an error. So I decided I do not want to use gmail anymore for this. I am sending email from a fake account just for sending emails so the security for it doesn't matter to me.

So how do change the code above so that it works for a different emailing service that is more reliable for sending emails in python/code?

The idea answer would contain be self contained and contain a sample script that works.


Edit1:

I've of course check to turn on less secure app feature on my fake gmail, copy paste text of what that page says:

Turn off less secure app access
Your account is vulnerable to malicious activity because you’re allowing apps & devices that use less secure sign-in technology to access your account. You should turn off this type of access. Google will automatically turn this setting OFF if it’s not being used. Learn more

there is also a yellow exclamation sign warning me.


Edit2

Output of EmailMessage():


it as suggested I paste this (empty message).

回答1:

I found the most reliable way to connect to google's SMTP server is via an app password.


How to get an app password

  1. go to manage my google account
  2. Under "Signing in to Google" confirm that "2-Step Verification" is "On" for the account.
  3. Also under "Signing in to Google" Select "App passwords".
  4. Select the app as "Mail" and the device as "Other (Custom name)" and name it.
  5. Copy the app password, it will be in a yellow box and looks like: "XXXX XXXX XXXX XXXX"

Using the app password in your code

import smtplib
from email.message import EmailMessage

def send_email_gmail(subject, message, destination):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    #This is where you would replace your password with the app password
    server.login('account@gmail.com', 'App_Password')

    msg = EmailMessage()

    message = f'{message}\n'
    msg.set_content(message)
    msg['Subject'] = subject
    msg['From'] = 'me123@gmail.com'
    msg['To'] = destination
    server.send_message(msg)

send_email_gmail('Test subject', 'This is the message', 'to_email@email.com')

Hope this helps!



回答2:

I have a function I use to send emails through yahoo. You don't need to pip install anything either.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def send_email(subject, to_email, message):
    password = "some_password"  # needs to be changed
    my_email = "some_email@yahoo.com"  # needs to be changed
    smtp_obj = smtplib.SMTP('smtp.mail.yahoo.com', 587)
    smtp_obj.starttls()
    smtp_obj.ehlo()
    smtp_obj.login(my_email, password)
    msg = MIMEMultipart()
    msg['From'] = my_email
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(message, 'plain'))
    smtp_obj.sendmail(msg['From'], msg['To'], msg.as_string())
    smtp_obj.quit()


if __name__ == '__main__':
    send_email('Subject: Automated e-mail', 'my_test_email@test.com', 'This was sent via script')

This is obviously the most basic format for an email with nothing more than a subject and body, but there is much more you can do. If you'd like to get more advanced read through the email and smtplib documentation from the standard library.



回答3:

For me it works like expected when I login using SSL, like so:

import smtplib, ssl
from email.mime.text import MIMEText


def send_email_gmail(subject, message, destination):
    # First assemble the message
    msg = MIMEText(message, 'plain')
    msg['Subject'] = subject

    # Login and send the message
    port = 465
    my_mail = 'me123@gmail.com'
    my_password = 'fakepassword111!!!'
    context = ssl.create_default_context() 
    with smtplib.SMTP_SSL('smtp.gmail.com', port, context=context) as server:
        server.login(my_mail, my_password)
        server.sendmail(my_mail, destination, msg.as_string())


send_email_gmail('Test subject', 'This is the message', 'to_email@email.com')

EDIT:

However, if you would really like to use another smtp server you could use outlook for instance. I got this to work without SSL, by connecting to smtp-mail.outlook.com on port 587, like so:

def send_email_gmail(subject, message, destination):
    # First assemble the message
    msg = MIMEText(message, 'plain')
    msg['Subject'] = subject

    # Login and send the message
    port = 587
    my_mail = 'my_mail@hotmail.com'
    my_password = 'my_password'
    with smtplib.SMTP('smtp-mail.outlook.com', port) as server:
        server.starttls()
        server.login(my_mail, my_password)
        server.sendmail(my_mail, destination, msg.as_string())

send_email_gmail('Test', 'Bericht', 'm.drillenburg@gmail.com')


回答4:

An advice to switch to another provider if you are not satisfied with the service provided by gmail is not complete without exploring other options.

You could send the message directly to the destination email server on TCP port 25. An SMTP server should accept a message for the "own" domain from any client without any authorization required. No problems with credentials here.

The address of that server can be obtained from DNS by looking up MX records (MX stands for mail exchanger) for the recipients's email domain. Usually there are several of them. The MX hosts have preferences (lowest number = highest preference) and for best results they should be contacted in the order from highest preference to the lowest until a mail is accepted.

The downsize is that you have to take care of retries if the first attempt fails - a mail queue is usually used for that purpose. Some sites use "graylisting" where the first attempt will fail as an anti-spam measure.

All that becomes less trival when there are multiple recipients in a message and such program becomes a tiny subset of a real SMTP server. You might even want to install a real server like Linux "postfix" and configure it send-only, there are tutorials available. Just be aware, that there are tons of configuration options.



回答5:

If you just want another email address, find the SMTP of your new email server.

server = smtplib.SMTP('smtp.newemail.com', port)
# replace the url and port with your new server's smtp.

The rest should be the same



标签: python email