标签: smtplib

Python 3 smtplib使用unicode字符发送

我在使用Python 3中的smtplib通过电子邮件发送unicode字符时遇到问题.这在3.1.1中失败,但在2.5.4中有效:

  import smtplib
  from email.mime.text import MIMEText

  sender = to = 'ABC@DEF.com'
  server = 'smtp.DEF.com'
  msg = MIMEText('€10')
  msg['Subject'] = 'Hello'
  msg['From'] = sender
  msg['To'] = to
  s = smtplib.SMTP(server)
  s.sendmail(sender, [to], msg.as_string())
  s.quit()
Run Code Online (Sandbox Code Playgroud)

我尝试了一些来自文档的例子,但也失败了. http://docs.python.org/3.1/library/email-examples.html,将目录内容作为MIME消息示例发送

有什么建议?

python email unicode smtplib python-3.x

8
推荐指数
1
解决办法
1万
查看次数

如何使用Python发送电子邮件?

我正在编写一个使用Python发送电子邮件的程序.我从各种论坛中学到的是以下代码:

#!/usr/bin/env python
import smtplib
sender = "sachinites@gmail.com"
receivers = ["abhisheks@cse.iitb.ac.in"]
yourname = "Abhishek Sagar"
recvname = "receptionist"
sub = "Testing email"
body = "who cares"
message = "From: " + yourname + "\n" 
message = message + "To: " + recvname + "\n"
message = message + "Subject: " + sub + "\n" 
message = message + body
try:
    print "Sending email to " + recvname + "...",
    server = smtplib.SMTP('smtp.gmail.com:587')
    username = 'XYZ@gmail.com'  
    password = '*****'  
    server.ehlo()
    server.starttls() …
Run Code Online (Sandbox Code Playgroud)

python email smtplib

8
推荐指数
2
解决办法
2万
查看次数

使用smtplib - Python接收来自Gmail的回复

好的,我正在研究一种类型的系统,以便我可以使用sms消息在我的计算机上开始操作.我可以让它发送初始消息:

import smtplib  

fromAdd = 'GmailFrom'  
toAdd  = 'SMSTo'  
msg = 'Options \nH - Help \nT - Terminal'  

username = 'GMail'  
password = 'Pass'  

server = smtplib.SMTP('smtp.gmail.com:587')  
server.starttls()  
server.login(username , password)  
server.sendmail(fromAdd , toAdd , msg)  
server.quit()
Run Code Online (Sandbox Code Playgroud)

我只需要知道如何等待回复或从Gmail本身提取回复,然后将其存储在变量中以供以后的功能使用.

python gmail smtplib reply

8
推荐指数
1
解决办法
7835
查看次数

如何使用python logging的SMTPHandler和SSL发送电子邮件

我正在开发一个烧瓶应用程序,我希望将错误级别日志记录发送到电子邮件地址.我尝试设置典型的错误处理程序:

mail_handler = SMTPHandler(mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                           fromaddr=app.config['MAIL_FROM_EMAIL'],
                           toaddrs=['me@my_address.com'],
                           subject='The server died. That sucks... :(',
                           credentials=(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']))
Run Code Online (Sandbox Code Playgroud)

请注意,配置值使用flask-mail设置,使用MAIL_USE_SSL=TrueMAIL_PORT=465.

但是,在调用错误时(在测试期间故意)我得到套接字超时错误 - 除了端口之外,我看不到如何告诉处理程序使用SSL.有一个secure=()参数可以传递(参见SMTPHandler文档),但它指定了我们的TLS,而不是SSL.

任何线索如何做到这一点?谢谢!

python ssl error-logging smtplib flask

8
推荐指数
1
解决办法
4923
查看次数

通过 Python 电子邮件库发送电子邮件会引发错误“预期字符串或类似字节的对象”

我正在尝试通过 python 3.6 中的一个简单函数将 csv 文件作为附件发送。

from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def email():


    msg = MIMEMultipart()
    msg['Subject'] = 'test'
    msg['From'] = 'test@gmail.com'
    msg['To'] = 'testee@gmail.com'
    msg.preamble = 'preamble'

    with open("test.csv") as fp:
        record = MIMEText(fp.read())
        msg.attach(record)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login("test@gmail.com", "password")
    server.sendmail("test@gmail.com", "testee@gmail.com", msg)
    server.quit()
Run Code Online (Sandbox Code Playgroud)

调用email()产生错误expected string or bytes-like object。重新定义server.sendmail("test@gmail.com", "testee@gmail.com", msg)server.sendmail("atest@gmail.com", "testee@gmail.com", msg.as_string()) 会导致发送电子邮件,但会在电子邮件正文中发送 csv 文件,而不是作为附件发送。谁能给我一些关于如何将 csv 文件作为附件发送的提示?

python csv email smtplib python-3.x

8
推荐指数
1
解决办法
4472
查看次数

Python 错误:5.7.0 必须先发出 starttls 命令

我尝试使用 python 脚本发送电子邮件,但收到错误消息:

5.7.0 must issue a starttls command first
Run Code Online (Sandbox Code Playgroud)

我正在使用smtplib,这是我的代码:

import smtplib

sender = 'from@fromdomain.com'
receivers = 'to@todomain.com'

message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
    smtpObj = smtplib.SMTP('smtp.gmail.com')
    smtpObj.sendmail(sender, receivers, message)         
    print "Successfully sent email"
except Exception,e:
    print str(e)
Run Code Online (Sandbox Code Playgroud)

如果有人知道如何解决此错误,我将不胜感激。

python email smtplib

7
推荐指数
1
解决办法
1万
查看次数

发送邮件 python asyncio

我正在尝试学习 asyncio。如果我在没有 asyncio 库的情况下正常运行这个程序,那么它需要更少的时间,而以这种方式需要更多的时间,那么这是使用 asyncio 发送邮件的正确方法还是还有其他方法?

import smtplib 
import ssl
import time
import asyncio


async def send_mail(receiver_email):
    try:
        print(f"trying..{receiver_email}")
        server = smtplib.SMTP(smtp_server, port)
        server.ehlo()
        server.starttls(context=context)
        server.ehlo()
        server.login(sender_email, password)
        message = "test"
        await asyncio.sleep(0)
        server.sendmail(sender_email, receiver_email, message)
        print(f"done...{receiver_email}")
    except Exception as e:
        print(e)
    finally:
        server.quit()

async def main():
     t1 = time.time()
     await asyncio.gather(
         send_mail("test@test.com"),
         send_mail("test@test.com"),
         send_mail("test@test.com"),
         send_mail("test@test.com")
     )
    print(f"End in {time.time() - t1}sec")

if __name__ == "__main__":
     smtp_server = "smtp.gmail.com"
     port = 587  # For starttls
     sender_email = "*****"
     password = …
Run Code Online (Sandbox Code Playgroud)

python asynchronous smtplib python-asyncio

7
推荐指数
1
解决办法
1万
查看次数

Outlook 2FA 的 SMTP 中继配置以从 python 脚本发送邮件

我正在尝试编写一个 python 脚本,该脚本将从具有 2 因素身份验证的 Office 365 帐户发送邮件。对于 smtp.office365.com,587,由于 2FA,它不起作用。

主机 = yourdomain-com.mail.protection.outlook.com 端口 = 25 应按照以下链接使用

https://docs.microsoft.com/en-us/exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-办公室-3

但我无法配置链接中提到的设置,因为我收到以下错误

您无权访问此页面或执行此操作。关闭支持信息关联 ID:sea#4d1521bd-d123-488f-9a37-fbf34425f13b 错误代码:0

有没有其他方法可以从具有 2 因素身份验证的 Office 365 帐户登录和发送邮件?

smtp smtplib python-3.x office365

7
推荐指数
0
解决办法
1107
查看次数

正确的mock.patch smtplib.SMTP方法

smtplib.SMTP.sendmail尝试在单元测试中模拟.修补调用。该sendmail方法似乎已成功模拟,我们可以将其查询为MagicMock,但sendmail 模拟的calledcalled_args属性未正确更新。看来我没有正确应用补丁。

这是我正在尝试的一个简化示例:

import unittest.mock
with unittest.mock.patch('smtplib.SMTP', autospec=True) as mock:
    import smtplib
    smtp = smtplib.SMTP('localhost')
    smtp.sendmail('me', 'me', 'hello world\n')
    mock.assert_called()           # <--- this succeeds
    mock.sendmail.assert_called()  # <--- this fails
Run Code Online (Sandbox Code Playgroud)

此示例生成:

AssertionError: Expected 'sendmail' to have been called.
Run Code Online (Sandbox Code Playgroud)

如果我将补丁更改为smtp.SMTP.sendmail;例如:

with unittest.mock.patch('smtplib.SMTP.sendmail.', autospec=True) as mock:
    ...
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我可以成功访问模拟的called_args和属性,但由于允许进行初始化,因此与主机建立了实际的 smtp 会话。这是单元测试,我不希望发生实际的网络。calledsmtplib.SMTP

python mocking smtplib

7
推荐指数
1
解决办法
4662
查看次数

如何创建 python 脚本,以便在目录中的 csv 文件在过去 24 小时内未更新时发送电子邮件?

我是 python 的新手,并试图了解如何自动化东西。我有一个文件夹,其中每天更新 5 个 csv 文件,但有时其中一两个文件不会在特定日期更新。我必须手动检查此文件夹。相反,我想以这种方式自动执行此操作,如果 csv 文件在过去 24 小时内没有更新,它可以向自己发送一封电子邮件,提醒我这一点。

我的代码:

import datetime
import glob
import os
import smtplib
import string
 
now  = datetime.datetime.today() #Get current date

list_of_files = glob.glob('c:/Python/*.csv') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime) #get latest file created in folder

newestFileCreationDate = datetime.datetime.utcfromtimestamp(os.path.getctime(latest_file)) # get creation datetime of last file

dif = (now - newestFileCreationDate) #calculating days between actual date and last creation date

logFile = "c:/Python/log.log" #defining a …
Run Code Online (Sandbox Code Playgroud)

python string operating-system glob smtplib

7
推荐指数
1
解决办法
544
查看次数