我正在尝试学习 asyncio。如果我在没有 asyncio 库的情况下正常运行这个程序,那么它需要更少的时间,而以这种方式需要更多的时间,那么这是使用 asyncio 发送邮件的正确方法还是还有其他方法?
import smtplib
import ssl
import time
import asyncio
async def send_mail(receiver_email):
try:
print(f"trying..{receiver_email}")
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls(context=context)
server.ehlo()
server.login(sender_email, password)
message = "test"
await asyncio.sleep(0)
server.sendmail(sender_email, receiver_email, message)
print(f"done...{receiver_email}")
except Exception as e:
print(e)
finally:
server.quit()
async def main():
t1 = time.time()
await asyncio.gather(
send_mail("test@test.com"),
send_mail("test@test.com"),
send_mail("test@test.com"),
send_mail("test@test.com")
)
print(f"End in {time.time() - t1}sec")
if __name__ == "__main__":
smtp_server = "smtp.gmail.com"
port = 587 # For starttls
sender_email = "*****"
password = …Run Code Online (Sandbox Code Playgroud)