У меня есть пароль приложения, созданный Google Mail (16 символов), при попытке отправить электронное письмо через smtp.gmail.com. Вот код Python, который я использую:
def send_html_email(to_email: str, subject: str):
"""
Send an HTML email using smtplib
"""
logging.debug(f"Preparing to send email to {to_email} with subject '{subject}'") # Log email details
# SMTP server configuration (you can set these as environment variables)
smtp_username = "Tokeri51" # Use sender_email from config
smtp_password = sender_password
if not smtp_username or not smtp_password:
raise ValueError("Sender email and password must be set in the configuration")
con = ssl.create_default_context()
logging.debug(f"SSL context created for secure connection {con}") # Log SSL context creation
# Create message
msg = MIMEMultipart('alternative')
msg\['Subject'\] = subject
msg\['From'\] = sender_email or smtp_username
msg\['To'\] = to_email
# Attach HTML content
# Create the email content using Jinja2 template
data = {
'username': "admin",
'reset_link': "https://example.com/reset-password?token=abc123",
'expiration_minutes': 30
}
# Set up Jinja2 environment to load templates from the templates directory
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('email_template.html')
# Render the template with the dynamic data
html_content = template.render(data)
logging.debug(f"Rendered HTML content") # Log the rendered HTML content for debugging
html_part = MIMEText(html_content, 'html')
msg.attach(html_part)
try:
# Create SMTP connection
logging.debug(f"Connecting to SMTP server {smtp_server}:{smtp_port}") # Log SMTP connection details
server = smtplib.SMTP(smtp_server, smtp_port)
logging.debug(f"Connected to SMTP server") # Log successful connection
server.starttls(context=con)
logging.debug(f"After TLS encryption")
logging.debug(f"Logging in to SMTP server as {sender_email} with {sender_password\[:4\]}\*\*\*\*") # Log login attempt
server.login(sender_email, smtp_password)
logging.debug(f"Logged in to SMTP server as {sender_email}") # Log successful login
# Send email
server.sendmail(sender_email, to_email, msg.as_string())
logging.debug(f"Email sent to {to_email}") # Log successful email sending
server.quit()
return {"message": "Email sent successfully"}
except Exception as e:
logging.error(f"Failed to send email: {str(e)}") # Log the error details
raise HTTPException(status_code=500, detail=f"Failed to send email: {str(e)}")
Вызов server.login завершается с ошибкой из-за неверных учетных данных.
У меня есть пароль приложения, созданный Google Mail (16 символов), при попытке отправить электронное письмо через smtp.gmail.com. Вот код Python, который я использую: [code]def send_html_email(to_email: str, subject: str): """ Send an HTML email using smtplib """ logging.debug(f"Preparing to send email to {to_email} with subject '{subject}'") # Log email details # SMTP server configuration (you can set these as environment variables) smtp_username = "Tokeri51" # Use sender_email from config smtp_password = sender_password
if not smtp_username or not smtp_password: raise ValueError("Sender email and password must be set in the configuration")
con = ssl.create_default_context() logging.debug(f"SSL context created for secure connection {con}") # Log SSL context creation # Create message msg = MIMEMultipart('alternative') msg\['Subject'\] = subject msg\['From'\] = sender_email or smtp_username msg\['To'\] = to_email
# Attach HTML content # Create the email content using Jinja2 template data = { 'username': "admin", 'reset_link': "https://example.com/reset-password?token=abc123", 'expiration_minutes': 30 }
# Set up Jinja2 environment to load templates from the templates directory env = Environment(loader=FileSystemLoader('templates')) template = env.get_template('email_template.html') # Render the template with the dynamic data html_content = template.render(data) logging.debug(f"Rendered HTML content") # Log the rendered HTML content for debugging html_part = MIMEText(html_content, 'html') msg.attach(html_part)
try: # Create SMTP connection logging.debug(f"Connecting to SMTP server {smtp_server}:{smtp_port}") # Log SMTP connection details server = smtplib.SMTP(smtp_server, smtp_port) logging.debug(f"Connected to SMTP server") # Log successful connection server.starttls(context=con) logging.debug(f"After TLS encryption") logging.debug(f"Logging in to SMTP server as {sender_email} with {sender_password\[:4\]}\*\*\*\*") # Log login attempt server.login(sender_email, smtp_password) logging.debug(f"Logged in to SMTP server as {sender_email}") # Log successful login # Send email server.sendmail(sender_email, to_email, msg.as_string()) logging.debug(f"Email sent to {to_email}") # Log successful email sending server.quit()
return {"message": "Email sent successfully"}
except Exception as e: logging.error(f"Failed to send email: {str(e)}") # Log the error details raise HTTPException(status_code=500, detail=f"Failed to send email: {str(e)}") [/code] Вызов server.login завершается с ошибкой из-за неверных учетных данных. [code]535, b'5.7.8 Username and Password not accepted.' [/code] [list] [*]Python версии 3.13.7