SMTP를 사용하여 Python에서 메일을 보내는 데 다음 방법을 사용하고 있습니다. 사용하기에 올바른 방법입니까?
from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('[email protected]', 'PASSWORD')
from_addr = "John Doe <[email protected]>"
to_addr = "[email protected]"
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 = '[email protected]_email_domain.net'
destination = ['[email protected]_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'] = '[email protected]'
msg['To'] = '[email protected]'
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('[email protected]', 'mypassword')
mailserver.sendmail('[email protected]','[email protected]',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('[email protected]', 'PASSWORD')
...
내가 볼 수있는 주요 문제점은 오류를 처리하지 않는다는 것입니다. 연결할 수 없음-아마도 기본 소켓 코드에 의해 예외가 발생했습니다.
다음 코드가 제대로 작동합니다.
import smtplib
to = '[email protected]'
gmail_user = '[email protected]'
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/
이건 어때?
import smtplib
SERVER = "localhost"
FROM = "[email protected]"
TO = ["[email protected]"] # 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()
SMTP를 차단하는 방화벽이 없는지 확인하십시오. 처음으로 전자 메일을 보내려고 할 때 Windows 방화벽과 McAfee 모두에서 전자 메일을 차단했습니다.
날짜를 올바른 형식 (- RFC2822 )으로 형식화해야합니다.
SMTP를 사용하여 메일을 보내려고 한 예제 코드입니다.
import smtplib, ssl
smtp_server = "smtp.gmail.com"
port = 587 # For starttls
sender_email = "[email protected]"
receiver_email = "[email protected]"
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 yagmail
yag = yagmail.SMTP('[email protected]', Host = 'YOUR.MAIL.SERVER', port = 26)
그런 다음 하나의 라이너입니다.
yag.send('[email protected]', 'hello', 'Hello\nThis is a mail from your server\n\nBye\n')
범위를 벗어나면 실제로 닫힙니다 (또는 수동으로 닫을 수 있음). 또한, 당신이 당신의 열쇠 고리에 사용자 이름을 등록 할 수 있도록 스크립트에 암호를 쓸 필요가 없습니다 (yagmail
!
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 = '[email protected]'
password = getpass('Enter Gmail password: ')
sender = '[email protected]'
destination = '[email protected]'
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)))
당신은 그렇게 할 수 있습니다
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 = '[email protected]'
to = '[email protected]'
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)