-1

我正在进行一个使用 python 的商业项目,我的团队将在某些团队中发送自动报告。发送它的代码效果很好:

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional

# To attach a file to the email (optional):
attachment  = "Path to the attachment"
mail.Attachments.Add(attachment)

mail.Send()

感谢这个线程:通过 Python 发送 Outlook 电子邮件?

无论如何要更改发件人的地址,例如:

mail.From = 'Team Adress'

否则问题将是人们会将邮件回复到我的电子邮件地址,这将是错误的做法。或者这根本不可能,因为它必须打开我的 Outlook 帐户?

4

1 回答 1

2

有两种可能的方式来指定发件人:

  1. 如果您在 Outlook 中配置了多个帐户,则可以使用MailItem.SendUsingAccount属性,该属性允许设置一个Account对象,该对象表示要在其下MailItem发送邮件的帐户。例如:
        public static void SendEmailFromAccount(Outlook.Application application, string subject, string body, string to, string smtpAddress) 
        { 

            // Create a new MailItem and set the To, Subject, and Body properties. 
            Outlook.MailItem newMail = (Outlook.MailItem)application.CreateItem(Outlook.OlItemType.olMailItem); 
            newMail.To = to; 
            newMail.Subject = subject; 
            newMail.Body = body; 

            // Retrieve the account that has the specific SMTP address. 
            Outlook.Account account = GetAccountForEmailAddress(application, smtpAddress); 
            // Use this account to send the email. 
            newMail.SendUsingAccount = account; 
            newMail.Send(); 
        } 


        public static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress) 
        { 

            // Loop over the Accounts collection of the current Outlook session. 
            Outlook.Accounts accounts = application.Session.Accounts; 
            foreach (Outlook.Account account in accounts) 
            { 
                // When the email address matches, return the account. 
                if (account.SmtpAddress == smtpAddress) 
                { 
                    return account; 
                } 
            } 
            throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", smtpAddress)); 
        } 
  1. MailItem.SentOnBehalfOfName属性允许设置一个字符串,指示邮件消息的预期发件人的显示名称。请注意,您需要获得许可才能代表他人发送任何内容。
于 2019-10-11T11:57:32.677 回答