Sending email in python

except smtplib, we can use zmail and yagmail.

  1. pip3 install zmail

    class ZMailObject(object):
    def __init__(self):
        self.username = '**@126.com'
        self.authorization_code = 'auth code'
        self.server = zmail.server(self.username, self.authorization_code)
        mail_body = {
        'subject': '***',
        'content_text': '***',  # text or HTML
        'attachments': ['./attachments/report.png'], }
        mail_to = "***"
        self.server.send_mail(mail_to, mail_body)
  2. pip3 install yagmail

    import yagmail
    yag_server = yagmail.SMTP(user='**@126.com', password='authorization_code', host='smtp.126.com')
    email_to = ['**@qq.com', ]
    email_title = '***'
    email_content = "***"
    email_attachments = ['./attachments/report.png', ]
    yag_server.send(email_to, email_title, email_content, email_attachments)
    yag_server.close()
  3. use smtplib and your gmail account to send email
    you need Turn on "Less secure app access" on your gmail account settings, then send it with code:

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    me = "youremail@gmail.com"
    my_password = r"****"
    you = "receiver@hotmail.com"
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Alert"
    msg['From'] = me
    msg['To'] = you
    html = '<html><body><p>Hi, I have the following alerts for you!</p></body></html>'
    part2 = MIMEText(html, 'html')
    msg.attach(part2)
    # Send the message via gmail's regular server, over SSL - passwords are being sent, afterall
    s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    # uncomment if interested in the actual smtp conversation
    # s.set_debuglevel(1)
    # do the smtp auth; sends ehlo if it hasn't been sent already
    s.login(me, my_password)
    s.sendmail(me, you, msg.as_string())
    s.quit()

Leave a Reply

Your email address will not be published. Required fields are marked *