尝试导入smtplib模块的语法错误

时间:2020-08-16 01:09:47

标签: python smtplib

我是python的新手,目前正尝试使用python脚本发送电子邮件。

我的问题是,当我尝试将smtplib模块导入我的代码时,出现了SyntaxError错误:

from email.headerregistry import Address
from email.message import EmailMessage
from smtplib
import os

#with open("liste.txt", "r") as body:
#    print(body.read())

email_address = os.getenv('GMAIL_ADDRESS', None)
email_password = os.getenv('GMAIL_APPLICATION_PASSWORD',None)

to_address = (
    Address(display_name = 'Test Name', username = 'testmail', domain = 'gmail.com'),
)

def create_email_message(from_address, to_address, subject, body):
    msg = EmailMessage()
    msg['From'] = from_address
    msg['To'] = to_address
    msg['Subject'] = subject
    msg.set_content(body)
    return msg

if __name__ == '__main__':
    msg = create_email_message(
        from_address = email_address,
        to_address = to_address,
        subject = 'Shopping list',
        body = 'Test grocery',
    )

    with smtplib.SMTP('smtp.gmail.com', port = 587) as smtp_server:
        smtp_server.ehlo()
        smtp_server.starttls()
        smtp_server.login(email_address, email_password)
        smtp_server.send_message(msg)

    print('Email sent succesfully')

我尝试在Google上搜索问题的答案,但没有任何运气。 我还尝试通过cmd安装smtplib,但发现它已经内置在python中了。

File "c:\Users\denni\OneDrive\Dokumenter\python\grocerylist.py", line 3
from smtplib
           ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:0)

import smtplib

from使用import

如果要使用from,则必须像上面一样将import x放在其后