programing

SMTP를 사용하여 Python에서 메일 보내기

elecom 2023. 9. 5. 19:39
반응형

SMTP를 사용하여 Python에서 메일 보내기

SMTP를 사용하여 Python에서 메일을 보내는 방법은 다음과 같습니다. 사용하는 방법이 맞나요? 누락된 gotchas가 있나요?

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()

제가 사용하는 스크립트는 매우 유사합니다. 이메일을 사용하는 방법의 예로 여기에 게시합니다.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 auth를 수행하려면 포트를 변경하고(587 사용) smtp.starttls()를 수행하면 됩니다.이것은 저에게 효과가 있었습니다.

...
smtp.connect('YOUR.MAIL.SERVER', 587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
...

이건 어때요?

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()

SMTP를 차단하는 방화벽이 없는지 확인합니다.처음 이메일을 보내려고 했을 때 Windows 방화벽과 McAfee에서 모두 차단되어 두 이메일을 모두 찾는 데 오랜 시간이 걸렸습니다.

주요 문제는 당신이 어떠한 오류도 처리하고 있지 않다는 것입니다..login()그리고..sendmail()둘 다 그들이 던질 수 있는 예외를 문서화했고, 그것은 마치..connect()연결할 수 없음을 나타내는 어떤 방법이 있어야 합니다. 기본 소켓 코드에서 예외가 발생했을 수 있습니다.

다음 코드는 나에게 잘 작동합니다.

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()
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/

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.message import EmailMessage
from getpass import getpass


password = getpass()

message = EmailMessage()
message.set_content('Message content here')
message['Subject'] = 'Your subject here'
message['From'] = "USERNAME@DOMAIN"
message['To'] = "you@mail.com"

try:
    smtp_server = None
    smtp_server = smtplib.SMTP("YOUR.MAIL.SERVER", 587)
    smtp_server.ehlo()
    smtp_server.starttls()
    smtp_server.ehlo()
    smtp_server.login("USERNAME@DOMAIN", password)
    smtp_server.send_message(message)
except Exception as e:
    print("Error: ", str(e))
finally:
    if smtp_server is not None:
        smtp_server.quit()

포트 465를 사용하려면 포트 465를 생성해야 합니다.SMTP_SSL물건.

올바른 형식(RFC2822)으로 날짜를 지정해야 합니다.

예를 바탕으로 다음과 같은 기능을 만들었습니다.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_email(host, port, user, pwd, recipients, subject, body, html=None, from_=None):
    """ copied and adapted from
        https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python#12424439
    returns None if all ok, but if problem then returns exception object
    """

    PORT_LIST = (25, 587, 465)

    FROM = from_ if from_ else user 
    TO = recipients if isinstance(recipients, (list, tuple)) else [recipients]
    SUBJECT = subject
    TEXT = body.encode("utf8") if isinstance(body, unicode) else body
    HTML = html.encode("utf8") if isinstance(html, unicode) else html

    if not html:
        # Prepare actual message
        message = """From: %s\nTo: %s\nSubject: %s\n\n%s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    else:
                # https://stackoverflow.com/questions/882712/sending-html-email-using-python#882770
        msg = MIMEMultipart('alternative')
        msg['Subject'] = SUBJECT
        msg['From'] = FROM
        msg['To'] = ", ".join(TO)

        # Record the MIME types of both parts - text/plain and text/html.
        # utf-8 -> https://stackoverflow.com/questions/5910104/python-how-to-send-utf-8-e-mail#5910530
        part1 = MIMEText(TEXT, 'plain', "utf-8")
        part2 = MIMEText(HTML, 'html', "utf-8")

        # Attach parts into message container.
        # According to RFC 2046, the last part of a multipart message, in this case
        # the HTML message, is best and preferred.
        msg.attach(part1)
        msg.attach(part2)

        message = msg.as_string()


    try:
        if port not in PORT_LIST: 
            raise Exception("Port %s not one of %s" % (port, PORT_LIST))

        if port in (465,):
            server = smtplib.SMTP_SSL(host, port)
        else:
            server = smtplib.SMTP(host, port)

        # optional
        server.ehlo()

        if port in (587,): 
            server.starttls()

        server.login(user, pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        # logger.info("SENT_EMAIL to %s: %s" % (recipients, subject))
    except Exception, ex:
        return ex

    return None

만일 당신이 통과한다면body그러면 일반 문자 메일이 보내질 것이지만, 만약 당신이 통과한다면.html와의 논쟁.body인수: html 전자 메일이 전송됩니다(html/html 유형을 지원하지 않는 전자 메일 클라이언트의 텍스트 콘텐츠에 대한 폴백 포함).

사용 예:

ex = send_email(
      host        = 'smtp.gmail.com'
   #, port        = 465 # OK
    , port        = 587  #OK
    , user        = "xxx@gmail.com"
    , pwd         = "xxx"
    , from_       = 'xxx@gmail.com'
    , recipients  = ['yyy@gmail.com']
    , subject     = "Test from python"
    , body        = "Test from python - body"
    )
if ex: 
    print("Mail sending failed: %s" % ex)
else:
    print("OK - mail sent"

Btw. 테스트 또는 프로덕션 SMTP 서버로 gmail을 사용하려면 보안 수준이 낮은 앱에 대한 임시 영구 액세스를 활성화하십시오.

  • 구글 메일/계정에 로그인
  • 다음 사이트로 이동: https://myaccount.google.com/lesssecureapps
  • 가능하게 하다
  • 이 기능 또는 유사한 기능을 사용하여 전자 메일 보내기
  • (권장) 다음 사이트로 이동합니다. https://myaccount.google.com/lesssecureapps
  • (권장) 사용 안 함

그 많은 긴 대답들을 보았습니까?두 줄로 나눠서 셀프 홍보를 할 수 있게 해주세요.

가져오기 및 연결:

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')

범위를 벗어나면(또는 수동으로 닫을 수 있음) 실제로 닫힙니다.쓸 당신의 이름을 할 수 입니다. (" 게가다, 가▁(▁prior▁further쓰it▁it▁(▁allow▁me▁really▁in▁will▁botheredring▁in▁such쓰정신나전▁you것게로▁your▁your다해▁toyagmail!)

패키지/설치, 팁 및 요령은 Python 2 및 3 모두에서 사용할 수 있는 git 또는 pip를 참조하십시오.

당신은 그렇게 할 수 있습니다.

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)))

madman2890을 기반으로 mailserver.quit()의 필요성을 제거하고 몇 가지를 업데이트했습니다.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text 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))

with smtplib.SMTP('smtp-mail.outlook.com',587) as mail_server:
    # identify ourselves to smtp gmail client
    mail_server.ehlo()
    # secure our email with tls encryption
    mail_server.starttls()
    # re-identify ourselves as an encrypted connection
    mail_server.ehlo()
    mail_server.login('me@gmail.com', 'mypassword')
    mail_server.sendmail('me@gmail.com','you@gmail.com',msg.as_string())

레드 메일은?

설치:

pip install redmail

그러면 그냥:

from redmail import EmailSender

# Configure the sender
email = EmailSender(
    host="YOUR.MAIL.SERVER", 
    port=26,
    username='me@example.com',
    password='<PASSWORD>'
)

# Send an email:
email.send(
    subject="An example email",
    sender="me@example.com",
    receivers=['you@example.com'],
    text="Hello!",
    html="<h1>Hello!</h1>"
)

많은 기능이 있습니다.

링크:

언급URL : https://stackoverflow.com/questions/64505/sending-mail-from-python-using-smtp

반응형