简体   繁体   中英

Why doesn't my bot of sending Emails using smtplib work?

see the code below, every time i try to use this function, it does not work and i kinda don't know why, so somebody could give me a hand?

import smtplib

def send_email():
server = smtplib.SMTP('smtp.hotmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()

server.login('bot_piloto.test@hotmail.com', '*******')

subject = 'You have to see this, it is about your university'
body = 'look, these are yours pendenting homeworks: ' + name_teacher2 + ' and these are yours expired homeworks: '+ name_teacher
sender: 'bot_piloto.test@hotmail.com'
receiver: 'bot_piloto.test@hotmail.com'

msg =  f"Subject: {subject}\n\n{body}"

server.sendmail(
    sender,
    receiver,
    msg
)

server.quit()

This is pretty different from your original code, but this is the method thay I've found works for me. Use it or don't, but this method is pretty reliable.

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

def send_email():
    subject = 'You have to see this, it is about your university'
    body = 'look, these are yours pendenting homeworks: ' + name_teacher2 + ' and these are yours expired homeworks: '+ name_teacher
    sender = 'bot_piloto.test@hotmail.com'
    receiver = 'bot_piloto.test@hotmail.com'

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = receiver

    body = MIMEText(body, "plain")
    msg.attach(body)

    #Create secure connection with server and send email
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.hotmail.com", 587, context=context) as server:
        server.login(sender, "*******")
        server.sendmail(
            sender,
            receiver,
            msg.as_string()
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM