使用python的outlook邮箱的From地址中的类型不匹配



我已经提到了这篇文章。请不要把它标记为重复。

我的outlook应用程序中有两个帐户(user1@org.com-默认配置文件,user2@org.com(

我正试图从user2@org.com(我的邮箱中配置的自动邮箱(部门邮箱((发送电子邮件

当我尝试以下时

for acc in outlook.Session.Accounts:
print(acc)  

它打印两个电子邮件帐户,即user1@org.comuser2@org.com

然而,当我进行以下时

outlook.Session.Accounts[0]
outlook.Session.Accounts[1]

它返回以下消息

<COMObject <unknown>> #but in for loop above, it returns the name of email account

所以,我终于做了下面的

From = 'user2@org.com' # I manually entered the from address
mail.To = 'test@org.com'
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(最近的调用last(C:\Users\user~1\AppData\Local\Temp/ipyernel_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 = 'user2@org.com'
receivers = ['user1@example.com']

port = 25
msg = MIMEText('This is test mail')
msg['Subject'] = 'Test mail'
msg['From'] = 'admin@example.com'
msg['To'] = 'info@example.com'
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属性。

手动输入的电子邮件地址是字符串类型,不能指定为发件人帐户。您需要它是与邮件项目相同的对象类型-<类'win32com.client.CDispatch'>

message = 'xyz'
preferred_account = 'user2@org.com'
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()

最新更新