Python send email exchange

supplement

2) SSL encryption: The port number is 465 , Communication process encryption, mail data security.

server = smtplib.SMTP_SSL(smtp_sever,465) 

3) TLS encryption: The port number is 587 , Communication process is encrypted, mail data is secure, using normal SMTP ports. For TLS encryption, you need to build firstSSL connection, Then send an email.Use starttls() To establish a secure connection

server = smtplib.SMTP(smtp_sever,587) server.starttls() 

Different mailbox support different encryption protocols, commonly supported mailbox supportEncryptionCorrespondenceThe port numberas follows:

mailbox SMTP server The port number Support encryption method
163 25/465 Plate / SSL encryption
126 smtp.126.com 25/465 Plate / SSL encryption
QQ 25/465/587 / SSL encryption / TLS encryption
Gmail smtp.gmail.com 587 TLS encryption

Log in to Gmail FAQ

If used gmail As a sender, in addition to the SMTP server to be changed smtp.gmail.com In addition, you need to change the port to 587 The password can be used directly using Gmail’s login password. But stillMay login failure. The reason is currentGMAIL controls access to the low security applicationWe need to be set manually.Click to use access to Applications with lower Gmail security, Click the interface as follows, set it to enable.

Читайте также:  Абстрактные классы java для чего

Exchange Server sends an email

def Email(to, content): urllib3.disable_warnings() creds = Credentials( username='algex\spsaccount', password='Spsaccount' ) config = Configuration(server="smtp.algex.asmpt.com", credentials=creds, auth_type=NTLM) account = Account( primary_smtp_address='[email protected]', credentials=creds, autodiscover=False, config=config, access_type=DELEGATE ) m = Message( account=account, subject="Guest pass key generated", body=HTMLBody(content), to_recipients = [Mailbox(email_address=to)], cc_recipients = [Mailbox(email_address=cc)], ) m.send() 

Источник

Sending an Email on Microsoft Exchange with Python

Now that I’ve got a client connect to the Exchange server, I can actually use the SOAP API methods as documented in the WSDL and on Microsoft’s documentation.

Suds has great built-in methods and classes for working with SOAP, but as this post confirms, bugs in both Suds and EWS mean that I’ll have to manually build the XML and inject it directly into the message.

So far, I have code that will connect a Suds client to my exchange server and send an XML message:

import ewsclient #Changes to Suds to make it EWS compliant import ewsclient.monkey # More Suds changes import datetime import os import sys import suds.client import logging import time from suds.transport.https import WindowsHttpAuthenticated #Uncomment below to turn on logging #logging.basicConfig(level=logging.DEBUG) #Logging on/accessing EWS SOAP API domain = 'exchange server' username = r'DOMAIN\username' password = 'password' transport = WindowsHttpAuthenticated(username=username, password=password) client = suds.client.Client("https://%s/EWS/Services.wsdl" % domain, transport=transport, plugins=[ewsclient.AddService()]) #Now that the SOAP client is connected to EWS, send this XML soap message client.service.CreateItem(__inject='msg':xml>)

Now, we just need to tell it what to send in that message.

Building the XML Message

There are all kinds of things you can talk to EWS about, but I just want to talk about emails.

I started with a template message from Microsoft and changed a few things.

First, I wanted to place a copy in my SentItems folder, so I added

In my first iteration, I had the body sent as text but I wanted to replace it with an HTML email template to make it prettier. This was tough for me to figure out; I kept getting XML validation errors. Eventually, I learned about CDATA, a tag that tells the XML parser to ignore whatever’s inside it.

I replaced the Body tag with:

And will replace the #Body# with some HTML from an email template later. Lastly, I put in some information about an automatic Reminder to get the final message:

  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">  MessageDisposition="SendAndSaveCopy" xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">  Id="sentitems" />    IPM.Note Python EWS Bot #SubjectDate#  BodyType="HTML"> #ReminderDate#T11:00:00-06:00 1 180   email@domain.com   false     

Each of those #Variable# tags I put in the XML will be string-replaced on the Python side.

Putting Variables into the Message

I wrote a quick little function to take a list of tuples and a template text and replace the text in the template:

#Replacing the text in the XML SOAP message def xmlreplace(text,list): for i in list: if i[0] in text: text = text.replace(i[0],str(i[1])) return text #Make a string out of the current time curdatetime = time.strftime("%c") #Set the Reminder Date for one week from today reminderday = datetime.date.today()+datetime.timedelta(days=7) #Open an HTML file to use as the body template = (open(file, 'r')) body = template.read() #List of parameters in the XML to replace: (template, replacement). xmlparams=[('#SubjectDate#',curdatetime),('#Body#', body),('#ReminderDate#',reminderday)] # Replace everything in the XML template shown above with the new dynamic values xml = xmlreplace(xmltemplate,xmlparams)

Now that I have XML as a big string, I can send my message:

Источник

Русские Блоги

Используйте Python для отправки личных почтовых ящиков и корпоративных почтовых ящиков, и как использовать Exchange Server для отправки электронных писем

Для протоколов почтового ящика и обще используемых конфигураций сервера, см.here

Это немного отличается от кода использования личных почтовых ящиков и корпоративных почтовых ящиков

Используйте личный почтовый ящик, QQ в качестве примера

Пароль использует код авторизации QQ для ввода веб-версии QQ Mailbox-> Служба SMTP можно увидеть по номеру учетной записи

#Результаты уведомления по почте for stu in student: smtpObj = smtplib.SMTP('smtp.qq.com', 587) # Smtpobj.set_debuglevel (1) # Удобная отладка smtpObj.ehlo() smtpObj.starttls() scoresend = str(int(exam) * int(exam_proportion) / 100 + int(dailyscore) * int( dailyscore_proportion) / 100 + int(homework) * int(homework_proportion) / 100 + int( checkscore) * int(checkscore_proportion) / 100 + int(experiment) * int( experiment_proportion) / 100) Текст = 'Тема:' + coursetitle + 'Оценка:' + Coreserend # Содержание электронной почты msg = MIMEText(text) if float(scoresend) >= 60: msg['Subject'] = u'Score Indicate' else: msg['Subject'] = u'WARNING' #Suts exmple к вашему номеру QQ msg['From'] = '[email protected]' msg['To'] = stu.email #Перейдите пример для вашего номера QQ и заполните пароль. Пароль здесь не пароль QQ, а авторизованный код Tencent smtpobj.login ('[email protected]', 'код авторизации') smtpObj.sendmail(msg['From'], msg['To'], msg.as_string()) smtpObj.quit() 

Энтерправомерный почтовый ящик

Если вы используете корпоративный почтовый ящик, вам нужно smtpObj = smtplib.SMTP(‘smtp.qq.com’, 587) Заменять smtpObj = smtplib.SMTP_SSL(‘smtp.exmail.qq.com’, 465) 。
Кроме того, необходимо аннотировать следующие две строки кода:

# smtpObj.ehlo() # smtpObj.starttls() 

Обратите внимание, что пароль почтового ящика компании не является авторизованным кодом, это пароль для входа в систему

smtpObj = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465) # smtpObj.ehlo() # smtpObj.starttls() context['site'] = site_url() context['site_name'] = config.site_name message = render_to_string(template_name, context) subject = ''.join(subject.splitlines()) msg = MIMEText(message) msg['Subject'] = subject msg ['from'] = 'Enterprise Mailbox Account' msg['To'] = to[0] smtpobj.login ('учетная запись Mailbox Enterprise', 'Password Mailbox Enterprise') smtpObj.sendmail(msg['From'], msg['To'], msg.as_string()) smtpObj.quit() 

Пополнить

Общий метод шифрования SMTP -почтового ящика

Используйте приведенный выше протокол SMTP, чтобы отправить электронные письма для отправки четких электронных писем. Если вы хотите зашифровать, есть несколько способов.
1) Передача Мингху:Номер порта 25 。

server = smtplib.SMTP(smtp_sever,25) 

2) шифрование SSL: Номер порта 465 , Crypt By Communication Process, почтовые данные безопасны.

server = smtplib.SMTP_SSL(smtp_sever,465) 

3) шифрование TLS: Номер порта 587 , Crypt By Communication Process, безопасные данные электронной почты, используйте обычные порты SMTP. Для метода шифрования TLS вам нужно сначала установить егоSSL Connection, А затем отправьте электронное письмо.Используйте здесь starttls() Приходите установить безопасную связь

server = smtplib.SMTP(smtp_sever,587) server.starttls() 

Различные почтовые ящики поддерживают различные протоколы шифрования и обычно используемая поддержка почтового ящикаШифрованиеВести перепискуНомер портаследующим образом:

Почта SMTP -сервер Номер порта Поддержка метода шифрования
163 smtp.163.com 25/465 Шифрование Mingshin/SSL
126 smtp.126.com 25/465 Шифрование Mingshin/SSL
QQ smtp.qq.com 25/465/587 Шифрование Mingshin/SSL/TLS шифрование
Gmail smtp.gmail.com 587 Шифрование TLS

Войдите в Gmail Часто задаваемые вопросы

Если используется gmail Как отправитель, в дополнение к SMTP -серверу, он должен быть изменен на smtp.gmail.com Кроме того, вам нужно изменить порт на 587 Пароль можно использовать непосредственно, используя пароль входа Gmail. Все ещеМожет войти в систему, чтобы пройтиСущность Причина в текущемРазрешения Gmail на доступ к приложениям с низким содержанием безопасности управления приложениями безопасностиНам нужно установить вручную.Нажмите, чтобы установить разрешения на доступ для применения приложений с низким уровнем безопасности Gmail, Нажмите на интерфейс следующим образом, установите настройки.

Exchange Server Отправить электронное письмо

def Email(to, content): urllib3.disable_warnings() creds = Credentials( username='algex\spsaccount', password='Spsaccount' ) config = Configuration(server="smtp.algex.asmpt.com", credentials=creds, auth_type=NTLM) account = Account( primary_smtp_address='[email protected]', credentials=creds, autodiscover=False, config=config, access_type=DELEGATE ) m = Message( account=account, subject="Guest pass key generated", body=HTMLBody(content), to_recipients = [Mailbox(email_address=to)], cc_recipients = [Mailbox(email_address=cc)], ) m.send() 

Источник

Оцените статью