add sender's name in the from field of the email in python

后端 未结 6 1566
忘掉有多难
忘掉有多难 2020-12-31 12:17

I am trying to send email with below code.

import smtplib
from email.mime.text import MIMEText

sender = \'sender@sender.com\'

def mail_me(cont, receiver):
         


        
6条回答
  •  无人及你
    2020-12-31 12:26

    Just tested the following code with gmx.com and it works fine. Although, whether you get the same mileage is a moot point.
    I have replaced all references to my email service with gmail

    #!/usr/bin/python
    
    #from smtplib import SMTP # Standard connection
    from smtplib import SMTP_SSL as SMTP #SSL connection
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    
    sender = 'example@gmail.com'
    receivers = ['example@gmail.com']
    
    
    msg = MIMEMultipart()
    msg['From'] = 'example@gmail.com'
    msg['To'] = 'example@gmail.com'
    msg['Subject'] = 'simple email via python test 1'
    message = 'This is the body of the email line 1\nLine 2\nEnd'
    msg.attach(MIMEText(message))
    
    ServerConnect = False
    try:
        smtp_server = SMTP('smtp.gmail.com','465')
        smtp_server.login('#name#@gmail.com', '#password#')
        ServerConnect = True
    except SMTPHeloError as e:
        print "Server did not reply"
    except SMTPAuthenticationError as e:
        print "Incorrect username/password combination"
    except SMTPException as e:
        print "Authentication failed"
    
    if ServerConnect == True:
        try:
            smtp_server.sendmail(sender, receivers, msg.as_string())
            print "Successfully sent email"
        except SMTPException as e:
            print "Error: unable to send email", e
        finally:
            smtp_server.close()
    

提交回复
热议问题