无法使用python将日历(书本日历)发送到outlook。ics文件仅通过普通电子邮件作为附件发送

2024-06-26 10:03:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要发送日历邀请和预定日历的被邀请者在一次去。相反,我的python代码只能通过普通电子邮件发送ics文件作为附件。这是我的密码。我正在尝试通过outlook发送日历邀请。这是outlook正在阻止的吗

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
import os,datetime


def send_invite(param):
    CRLF = "\r\n"
    #attendees = param['to']
    attendees = ""
    try:
        for att in param['To']:
            attendees += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN="+att+";X-NUM-GUESTS=0:mailto:"+att+CRLF
    except Exception as e:
        print("attendee error",e)

    msg = MIMEMultipart('mixed')
    msg['Reply-To'] = param['from']
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = param['subject']
    msg['From'] = param['from']
    msg['To'] = attendees
    msg['Content-class'] = "urn:content-classes:calendarmessage"

    __location__ = os.path.relpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__))
    )
    f = os.path.join(__location__, 'invite.ics')
    ics_content = open(f).read()
    try:
        replaced_contents = ics_content.replace('startDate', param['meetingStartDate'])
        replaced_contents = replaced_contents.replace('endDate', param['meetingEndDate'])
        replaced_contents = replaced_contents.replace('telephonic', param['location'])
        replaced_contents = replaced_contents.replace('now', datetime.datetime.now().strftime("%Y%m%d%T%H%M%SZ"))
    except Exception as e:
        print("replace error",e)
    if param['description'] != None:
        replaced_contents = replaced_contents.replace('describe', param.get('description'))
    else:
        replaced_contents = replaced_contents.replace('describe', '')
    replaced_contents = replaced_contents.replace('attend', msg['To'])
    replaced_contents = replaced_contents.replace('subject', param['subject'])
    part_email = MIMEText(replaced_contents,'calender;method=REQUEST')

    msgAlternative = MIMEMultipart('alternative')

    ical_atch = MIMEBase('text/calender',' ;name="%s"'%"invite.ics")
    ical_atch.set_payload(replaced_contents)
    encoders.encode_base64(ical_atch)
    ical_atch.add_header('Content-Disposition','attachment; filename="%s"'%f)

    msgAlternative.attach(part_email)
    msgAlternative.attach(ical_atch)
    msg.attach(msgAlternative)
    mailServer = smtplib.SMTP(f'{param["SMTP_server"]}', 25)
    mailServer.ehlo()
    #mailServer.starttls()
    #mailServer.ehlo()
    #mailServer.login(login, password)
    mailServer.sendmail(param['from'], param['To'], msg.as_string())
    mailServer.close()

Tags: tofromimportparamosemailcontentsmsg