문제
저는 SMTP를 사용하여 Python에서 메일을 보내려면 다음 방법을 사용하고 있습니다.사용하는 것이 올바른 방법입니까, 아니면 제가 놓친 문제가 있습니까?
from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
from_addr = "John Doe <john@doe.net>"
to_addr = "foo@bar.com"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
해결책
내가 사용하는 스크립트는 매우 유사합니다.email.* 모듈을 사용하여 MIME 메시지를 생성하는 방법의 예로 여기에 게시합니다.따라서 이 스크립트를 쉽게 수정하여 그림 등을 첨부할 수 있습니다.
나는 ISP에 의존하여 날짜 시간 헤더를 추가합니다.
내 ISP에서는 보안 smtp 연결을 사용하여 메일을 보낼 것을 요구합니다. 저는 smtplib 모듈(다운로드 가능)을 사용합니다. http://www1.cs.columbia.edu/~db2501/ssmtplib.py)
스크립트에서와 마찬가지로 SMTP 서버에서 인증하는 데 사용되는 사용자 이름과 비밀번호(아래에 주어진 더미 값)는 소스에서 일반 텍스트로 되어 있습니다.이는 보안상의 약점입니다.그러나 최선의 대안은 이를 보호하기 위해 얼마나 주의를 기울여야 하는지(원합니까?)에 달려 있습니다.
=======================================
#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = 'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except:
sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message
다른 팁
제가 자주 사용하는 방법은..별로 다르지는 않지만 조금은
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
msg = MIMEMultipart()
msg['From'] = 'me@gmail.com'
msg['To'] = 'you@gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('me@gmail.com', 'mypassword')
mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string())
mailserver.quit()
그게 다야
또한 SSL이 아닌 TLS로 smtp 인증을 수행하려면 포트를 변경하고(587 사용) smtp.starttls()를 수행하면 됩니다.이것은 나에게 효과적이었습니다.
...
smtp.connect('YOUR.MAIL.SERVER', 587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
...
내가 본 가장 큰 문제점은 오류를 처리하지 않는다는 것입니다..login() 및 .sendmail() 둘 다 발생할 수 있는 예외가 문서화되어 있으며 .connect()에는 연결할 수 없음을 나타내는 방법이 있어야 하는 것처럼 보입니다. 아마도 기본 소켓 코드에서 발생한 예외일 것입니다.
SMTP를 차단하는 방화벽이 없는지 확인하세요.처음으로 이메일을 보내려고 했을 때 Windows 방화벽과 McAfee가 모두 차단했기 때문에 두 가지를 모두 찾는 데 시간이 오래 걸렸습니다.
이건 어때?
import smtplib
SERVER = "localhost"
FROM = "sender@example.com"
TO = ["user@example.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(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
다음 코드는 나에게 잘 작동합니다.
import smtplib
to = 'mkyong2002@yahoo.com'
gmail_user = 'mkyong2002@gmail.com'
gmail_pwd = 'yourpassword'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo() # extra characters to permit edit
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.quit()
참조: http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/
날짜 형식을 올바른 형식으로 지정했는지 확인해야 합니다. RFC2822.
긴 답변을 모두 보셨나요?몇 줄로 모든 작업을 수행하여 자체 홍보할 수 있게 해주세요.
가져오기 및 연결:
import yagmail
yag = yagmail.SMTP('john@doe.net', host = 'YOUR.MAIL.SERVER', port = 26)
그러면 그것은 단지 하나의 라이너입니다.
yag.send('foo@bar.com', 'hello', 'Hello\nThis is a mail from your server\n\nBye\n')
범위를 벗어나면 실제로 닫힙니다(또는 수동으로 닫을 수도 있음).게다가, 키링에 사용자 이름을 등록할 수 있으므로 스크립트에 비밀번호를 적을 필요가 없습니다. (글을 쓰기 전에 정말 귀찮았습니다.) yagmail
!)
패키지/설치에 대한 팁과 요령을 살펴보십시오. 자식 또는 씨, Python 2와 3 모두에서 사용할 수 있습니다.
SMTP를 사용하여 메일을 보내기 위해 수행한 예제 코드입니다.
import smtplib, ssl
smtp_server = "smtp.gmail.com"
port = 587 # For starttls
sender_email = "sender@email"
receiver_email = "receiver@email"
password = "<your password here>"
message = """ Subject: Hi there
This message is sent from Python."""
# Create a secure SSL context
context = ssl.create_default_context()
# Try to log in to server and send email
server = smtplib.SMTP(smtp_server,port)
try:
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
넌 그렇게 할 수 있어
import smtplib
from email.mime.text import MIMEText
from email.header import Header
server = smtplib.SMTP('mail.servername.com', 25)
server.ehlo()
server.starttls()
server.login('username', 'password')
from = 'me@servername.com'
to = 'mygfriend@servername.com'
body = 'That A Message For My Girl Friend For tell Him If We will go to eat Something This Nigth'
subject = 'Invite to A Diner'
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
message = msg.as_string()
server.sendmail(from, to, message)
다음은 Python 3.x의 실제 예제입니다.
#!/usr/bin/env python3
from email.message import EmailMessage
from getpass import getpass
from smtplib import SMTP_SSL
from sys import exit
smtp_server = 'smtp.gmail.com'
username = 'your_email_address@gmail.com'
password = getpass('Enter Gmail password: ')
sender = 'your_email_address@gmail.com'
destination = 'recipient_email_address@gmail.com'
subject = 'Sent from Python 3.x'
content = 'Hello! This was sent to you via Python 3.x!'
# Create a text/plain message
msg = EmailMessage()
msg.set_content(content)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = destination
try:
s = SMTP_SSL(smtp_server)
s.login(username, password)
try:
s.send_message(msg)
finally:
s.quit()
except Exception as E:
exit('Mail failed: {}'.format(str(E)))