파이썬으로 이메일을 보내는 방법?
이 코드는 작동하며 전자 메일을 보냅니다.
import smtplib
#SERVER = "localhost"
FROM = 'monty@python.com'
TO = ["jon@mycompany.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP('myserver')
server.sendmail(FROM, TO, message)
server.quit()
그러나 다음과 같은 함수로 감싸려고하면 :
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
"""this is some test documentation in the function"""
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
그것을 호출하면 다음과 같은 오류가 발생합니다.
Traceback (most recent call last):
File "C:/Python31/mailtest1.py", line 8, in <module>
sendmail.sendMail(sender,recipients,subject,body,server)
File "C:/Python31\sendmail.py", line 13, in sendMail
server.sendmail(FROM, TO, message)
File "C:\Python31\lib\smtplib.py", line 720, in sendmail
self.rset()
File "C:\Python31\lib\smtplib.py", line 444, in rset
return self.docmd("rset")
File "C:\Python31\lib\smtplib.py", line 368, in docmd
return self.getreply()
File "C:\Python31\lib\smtplib.py", line 345, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
누구든지 왜 내가 이해하도록 도울 수 있습니까?
표준 패키지 email
를 smtplib
함께 사용하여 전자 메일을 보내는 것이 좋습니다 . 다음 예제를 살펴보십시오 ( Python 문서 에서 재현 됨 ). 이 접근 방식을 따르면 "간단한"작업이 간단하고 이진 개체 첨부 또는 일반 / HTML 멀티 파트 메시지 전송과 같은보다 복잡한 작업이 매우 빠르게 수행됩니다.
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
with open(textfile, 'rb') as fp:
# Create a text/plain message
msg = MIMEText(fp.read())
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
여러 대상으로 전자 메일을 보내려면 Python 설명서 의 예제를 따르십시오 .
# Import smtplib for the actual sending function
import smtplib
# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'
# Assume we know that the image files are all in PNG format
for file in pngfiles:
# Open the files in binary mode. Let the MIMEImage class automatically
# guess the specific image type.
with open(file, 'rb') as fp:
img = MIMEImage(fp.read())
msg.attach(img)
# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()
보시다시피 To
, MIMEText
객체 의 헤더 는 쉼표로 구분 된 이메일 주소로 구성된 문자열이어야합니다. 반면, sendmail
함수에 대한 두 번째 인수 는 문자열 목록이어야합니다 (각 문자열은 전자 메일 주소 임).
세 개의 이메일 주소가 경우에 따라서, : person1@example.com
, person2@example.com
, 그리고 person3@example.com
, 당신이 할 수있는 등 (명백한 부분은 생략) 다음과 같습니다 :
to = ["person1@example.com", "person2@example.com", "person3@example.com"]
msg['To'] = ",".join(to)
s.sendmail(me, to, msg.as_string())
이 "","".join(to)
부분은 목록에서 단일 문자열을 쉼표로 구분하여 만듭니다.
당신의 질문에서 나는 당신이 파이썬 튜토리얼 을 겪지 않았다는 것을 모았습니다 -파이썬의 어느 곳에서나 가고 싶다면 반드시 있어야합니다-문서는 대부분 표준 라이브러리에 탁월합니다.
글쎄, 당신은 최신의 현대적인 답변을 원합니다.
내 대답은 다음과 같습니다.
파이썬으로 메일을 보내야 할 때 메일 건 API를 사용하면 메일을 정렬하는 데 많은 어려움을 겪 습니다. 그들은 멋진 앱 / API를 가지고있어 매월 10,000 개의 이메일을 무료로 보낼 수 있습니다.
이메일을 보내는 것은 다음과 같습니다 :
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api", "YOUR_API_KEY"),
data={"from": "Excited User <mailgun@YOUR_DOMAIN_NAME>",
"to": ["bar@example.com", "YOU@YOUR_DOMAIN_NAME"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
이벤트 및 기타 정보를 추적 할 수도 있습니다 . 빠른 시작 안내서를 참조하십시오 .
이 정보가 도움이 되길 바랍니다.
yagmail 패키지를 조언하여 이메일을 보내는 데 도움을 드리고 싶습니다 (관리자입니다. 광고에 대해 유감 스럽지만 실제로 도움이 될 수 있다고 생각합니다!).
전체 코드는 다음과 같습니다.
import yagmail
yag = yagmail.SMTP(FROM, 'pass')
yag.send(TO, SUBJECT, TEXT)
모든 인수에 대한 기본값을 제공합니다. 예를 들어 자신에게 보내려는 TO
경우 생략 할 수 있습니다. 주제를 원하지 않는 경우 생략 할 수도 있습니다.
또한, 목표는 HTML 코드 나 이미지 (및 기타 파일)를 실제로 쉽게 첨부 할 수 있도록하는 것입니다.
내용을 넣는 위치는 다음과 같습니다.
contents = ['Body text, and here is an embedded image:', 'http://somedomain/image.png',
'You can also find an audio file attached.', '/local/path/song.mp3']
와우, 첨부 파일을 보내는 것이 얼마나 쉬운가요! 이것은 yagmail없이 20 줄을 취할 것입니다.)
또한 비밀번호를 한 번 설정하면 비밀번호를 다시 입력 할 필요가 없으며 안전하게 저장해야합니다. 귀하의 경우 다음과 같이 할 수 있습니다 :
import yagmail
yagmail.SMTP().send(contents = contents)
훨씬 더 간결합니다!
github을 보거나으로 직접 설치 하도록 초대합니다 pip install yagmail
.
들여 쓰기 문제가 있습니다. 아래 코드는 작동합니다 :
import textwrap
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
"""this is some test documentation in the function"""
message = textwrap.dedent("""\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT))
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
이 시도:
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
"""this is some test documentation in the function"""
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
"New part"
server.starttls()
server.login('username', 'password')
server.sendmail(FROM, TO, message)
server.quit()
smtp.gmail.com에서 작동합니다.
함수에서 코드를 들여 쓰는 동안 (괜찮아) 원시 메시지 문자열의 줄도 들여 쓰기했습니다. 그러나 선행 공백은 RFC 2822 의 2.2.3 및 3.2.3 섹션에 설명 된대로 헤더 행의 접힘 (연결)을 나타냅니다 .
각 헤더 필드는 논리적으로 필드 이름, 콜론 및 필드 본문을 포함하는 한 줄의 문자입니다. 그러나 편의상, 라인 당 998/78 문자 제한을 처리하기 위해 헤더 필드의 필드 본문 부분을 여러 줄 표현으로 나눌 수 있습니다. 이것을 "폴딩"이라고합니다.
sendmail
호출 의 함수 형식 에서 모든 행은 공백으로 시작하므로 "펼쳐짐"(연결됨)으로 보내려고합니다.
From: monty@python.com To: jon@mycompany.com Subject: Hello! This message was sent with Python's smtplib.
우리의 마음이 시사하는 것보다 기타, smtplib
이해하지 못할 To:
및 Subject:
이러한 이름 만 줄의 시작 부분에 인식하고 있기 때문에, 더 이상 헤더를. 대신 smtplib
매우 긴 발신자 이메일 주소를 가정합니다.
monty@python.com To: jon@mycompany.com Subject: Hello! This message was sent with Python's smtplib.
이것은 작동하지 않으므로 예외가 발생합니다.
해결책은 간단합니다. 이전과 마찬가지로 message
문자열을 유지하십시오 . 이것은 Zeeshan이 제안한 기능에 의해 또는 소스 코드에서 바로 수행 될 수 있습니다.
import smtplib
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
"""this is some test documentation in the function"""
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
이제 전개가 일어나지 않고
From: monty@python.com
To: jon@mycompany.com
Subject: Hello!
This message was sent with Python's smtplib.
이것이 작동하고 이전 코드로 수행 된 작업입니다.
필자는 RFC의 3.5 섹션 (필수) 을 수용하기 위해 헤더와 본문 사이에 빈 줄을 유지하고 Python 스타일 가이드 PEP-0008 (선택 사항) 에 따라 포함을 함수 외부에 두었습니다 .
아마도 메시지에 탭을 넣을 수 있습니다. sendMail에 전달하기 전에 메시지를 인쇄하십시오.
다음은 Python 3.x
보다 간단한 예제입니다 2.x
.
import smtplib
from email.message import EmailMessage
def send_mail(to_email, subject, message, server='smtp.example.cn',
from_email='xx@example.com'):
# import smtplib
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ', '.join(to_email)
msg.set_content(message)
print(msg)
server = smtplib.SMTP(server)
server.set_debuglevel(1)
server.login(from_email, 'password') # user & password
server.send_message(msg)
server.quit()
print('successfully sent the mail.')
이 함수를 호출하십시오.
send_mail(to_email=['12345@qq.com', '12345@126.com'],
subject='hello', message='Your analysis has done!')
아래는 중국 사용자에게만 해당 될 수 있습니다.
126/163, 网易 邮箱을 사용하는 경우 아래와 같이 "客户 端 授权 密码"를 설정해야합니다.
참조 : https://stackoverflow.com/a/41470149/2803344 https://docs.python.org/3/library/email.examples.html#email-examples
Make sure you have granted permission for both Sender and Receiver to send email and receive email from Unknown sources(External Sources) in Email Account.
import smtplib
#Ports 465 and 587 are intended for email client to email server communication - sending email
server = smtplib.SMTP('smtp.gmail.com', 587)
#starttls() is a way to take an existing insecure connection and upgrade it to a secure connection using SSL/TLS.
server.starttls()
#Next, log in to the server
server.login("#email", "#password")
msg = "Hello! This Message was sent by the help of Python"
#Send the mail
server.sendmail("#Sender", "#Reciever", msg)
As far your code is concerned, there doesn't seem to be anything fundamentally wrong with it except that, it is unclear how you're actually calling that function. All I can think of is that when your server is not responding then you will get this SMTPServerDisconnected error. If you lookup the getreply() function in smtplib (excerpt below), you will get an idea.
def getreply(self):
"""Get a reply from the server.
Returns a tuple consisting of:
- server response code (e.g. '250', or such, if all goes well)
Note: returns -1 if it can't read response code.
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
Raises SMTPServerDisconnected if end-of-file is reached.
"""
check an example at https://github.com/rreddy80/sendEmails/blob/master/sendEmailAttachments.py that also uses a function call to send an email, if that's what you're trying to do (DRY approach).
Thought I'd put in my two bits here since I have just figured out how this works.
It appears that you don't have the port specified on your SERVER connection settings, this effected me a little bit when I was trying to connect to my SMTP server that isn't using the default port: 25.
According to the smtplib.SMTP docs, your ehlo or helo request/response should automatically be taken care of, so you shouldn't have to worry about this (but might be something to confirm if all else fails).
Another thing to ask yourself is have you allowed SMTP connections on your SMTP server itself? For some sites like GMAIL and ZOHO you have to actually go in and activate the IMAP connections within the email account. Your mail server might not allow SMTP connections that don't come from 'localhost' perhaps? Something to look into.
The final thing is you might want to try and initiate the connection on TLS. Most servers now require this type of authentication.
You'll see I've jammed two TO fields into my email. The msg['TO'] and msg['FROM'] msg dictionary items allows the correct information to show up in the headers of the email itself, which one sees on the receiving end of the email in the To/From fields (you might even be able to add a Reply To field in here. The TO and FROM fields themselves are what the server requires. I know I've heard of some email servers rejecting emails if they don't have the proper email headers in place.
This is the code I've used, in a function, that works for me to email the content of a *.txt file using my local computer and a remote SMTP server (ZOHO as shown):
def emailResults(folder, filename):
# body of the message
doc = folder + filename + '.txt'
with open(doc, 'r') as readText:
msg = MIMEText(readText.read())
# headers
TO = 'to_user@domain.com'
msg['To'] = TO
FROM = 'from_user@domain.com'
msg['From'] = FROM
msg['Subject'] = 'email subject |' + filename
# SMTP
send = smtplib.SMTP('smtp.zoho.com', 587)
send.starttls()
send.login('from_user@domain.com', 'password')
send.sendmail(FROM, TO, msg.as_string())
send.quit()
참고 URL : https://stackoverflow.com/questions/6270782/how-to-send-an-email-with-python
'IT' 카테고리의 다른 글
Git에서 커밋되지 않은 변경 사항 및 git diff를 자세히 표시하는 방법 (0) | 2020.06.10 |
---|---|
기존 리포지토리의 지점에서 새 GitHub 리포지토리를 생성하려면 어떻게해야합니까? (0) | 2020.06.10 |
속성과 속성의 차이점은 무엇입니까? (0) | 2020.06.10 |
Homebrew로 수식을 업데이트하려면 어떻게합니까? (0) | 2020.06.10 |
응용 프로그램 오류-서버 연결에 실패했습니다. (0) | 2020.06.10 |