我的 Outlook 应用程序中有 2 个帐户(
[email protected]
- 默认配置文件,[email protected]
)
我正在尝试从
[email protected]
(这是我的电子邮箱中配置的自动电子邮箱(部门电子邮箱))发送电子邮件
当我尝试以下操作时
for acc in outlook.Session.Accounts:
print(acc)
它会打印两个电子邮件帐户,即
[email protected]
和 [email protected]
但是,当我执行以下操作时
outlook.Session.Accounts[0]
outlook.Session.Accounts[1]
它返回以下消息
<COMObject <unknown>> #but in for loop above, it returns the name of email account
所以,我终于做了下面的事情
From = '[email protected]' # I manually entered the from address
mail.To = '[email protected]'
mail.Subject = 'Test Email'
mail.HTMLBody = '<h3>This is HTML Body</h3>'
mail._oleobj_.Invoke(*(64209, 0, 8, 0, From)) # this results in error
---------------------------------------------------------------------------------------- com_error Traceback(最近调用 最后)C:\Users\user~1\AppData\Local\Temp/ipykernel_14360/3581612401.py 在 ----> 1 封邮件。oleobj.Invoke(*(64209, 0, 8, 0, From))
com_error:(-2147352571,“类型不匹配。”,无,1)
如何正确分配From账户?
更新 - smtp 电子邮件脚本
import smtplib
from email.mime.text import MIMEText
sender = '[email protected]'
receivers = ['[email protected]']
port = 25
msg = MIMEText('This is test mail')
msg['Subject'] = 'Test mail'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
with smtplib.SMTP('mail-innal.org.com', port) as server:
# server.login('username', 'password')
server.sendmail(sender, receivers, msg.as_string())
print("Successfully sent email")
您正在打印一个 COM 对象,这没有任何意义 -
print
可能足够聪明,可以尝试检索默认对象属性(dispid = 0)。如果您需要一个有意义的名称,请使用 Account.DisplayName
。
您需要做的就是将
Account
对象存储在变量中并将其分配给 MailItem.SendUsingAccount
属性。
手动输入的邮箱地址是字符串类型,不能指定为发件人账户。您需要它与邮件项目具有相同的对象类型 -
message = 'xyz'
preferred_account = '[email protected]'
outlook = win32.Dispatch('Outlook.Application')
mail = outlook.CreateItem(0)
mail.Subject = subject
mail.Body = message
outlook_acc_to_use = None
for outlook_acc in outlook.Session.Accounts:
if preferred_account in str(outlook_acc):
outlook_acc_to_use = outlook_acc
break
if outlook_acc_to_use != None:
mail._oleobj_.Invoke(*(64209, 0, 8, 0, outlook_acc_to_use))
mail.To = '; '.join(receiver_emails)
mail.Send()