如何用Python结合HTML通过未登录的Outlook账户发送邮件
Great question! Let's break this down clearly: You cannot directly add a password to your existing Outlook COM automation code to send emails from an unlogged account (like from@outlook.com). Here's why, plus two practical workarounds:
Why Your Current Approach Won't Work
Outlook's COM automation API is tightly linked to accounts already configured in your desktop Outlook client. It doesn't support dynamically logging into an unadded account by passing a password in code—this is a security restriction to prevent unapproved credential misuse. All send operations rely on accounts that are already set up in Outlook (with credentials stored in Windows Credential Manager or Outlook's internal settings).
Also, there's a bug in your existing code: the line message=inbox.items.add overwrites the mail item you created with outlook.Createitem(0), which will cause errors. You should remove that line entirely.
Solution 1: Configure the Account in Outlook First
If you're okay with adding from@outlook.com to your Outlook client, you can modify your code to send from that account without hardcoding a password (Outlook will use the saved credentials). Here's the corrected code:
import win32com.client as client import time outlook = client.Dispatch("Outlook.Application") message = outlook.CreateItem(0) # Create a new mail item namespace = outlook.GetNameSpace('MAPI') # Locate the configured account you want to send from send_account = None for account in namespace.Accounts: if account.SmtpAddress == "from@outlook.com": send_account = account break if send_account: message.SendUsingAccount = send_account # Set the sending account message.To = "to@outlook.com" message.Subject = "Subject text here" message.BodyFormat = 2 message.HTMLBody = "<html><h2><span style='color:red'>There is an error with the file </span></h2> <body>Please check your submission and try again </body></html>" message.Save() message.Display() time.sleep(5) message.Send() else: print("Account not found in Outlook. Please add it first via Outlook's settings.")
Solution 2: Send via SMTP (No Outlook Client Required)
If you don't want to add the account to Outlook, use Python's built-in smtplib library to send directly through Outlook's SMTP server. This lets you use the account's password directly in code (just be careful with plaintext passwords—consider using environment variables or a secure secret manager instead of hardcoding).
Here's an example:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # Account credentials sender_email = "from@outlook.com" sender_password = "your_account_password_here" recipient_email = "to@outlook.com" # Build the email message msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = recipient_email msg['Subject'] = "Subject text here" # Add HTML content html_body = "<html><h2><span style='color:red'>There is an error with the file </span></h2> <body>Please check your submission and try again </body></html>" msg.attach(MIMEText(html_body, 'html')) # Send via Outlook's SMTP server try: with smtplib.SMTP('smtp.office365.com', 587) as server: server.starttls() # Enable secure TLS encryption server.login(sender_email, sender_password) server.send_message(msg) print("Email sent successfully!") except Exception as e: print(f"Error sending email: {str(e)}")
Key Note for SMTP
- Outlook's SMTP server requires TLS encryption on port 587.
- If you have two-factor authentication (2FA) enabled on your
from@outlook.comaccount, you'll need to use an app password instead of your regular account password.
内容的提问来源于stack exchange,提问作者Morgan18

