簡體   English   中英

為什么我的使用 smtplib 發送電子郵件的機器人不起作用?

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

請參閱下面的代碼,每次我嘗試使用這個 function 時,它都不起作用,我有點不知道為什么,所以有人可以幫幫我嗎?

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()

這與您的原始代碼完全不同,但這是我發現的適合我的方法。 使用或不使用它,但這種方法非常可靠。

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()
        )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM