IT HOW

무엇이는 물어보세요

컨텐츠로 건너뛰기
  • 프로그래밍
  • 파이썬
  • 자바
  • 자바스크립트
  • 리눅스
  • c#

Python을 사용하여 HTML 이메일 보내기 보내려면 어떻게해야합니까? 간단한 문자를 보낼

Python을 사용하여 HTML 컨텐츠를 이메일로 보내려면 어떻게해야합니까? 간단한 문자를 보낼 수 있습니다.



답변

에서 18.1.11 – 파이썬 v2.7.14 문서. 이메일 : 예 :

대체 일반 텍스트 버전으로 HTML 메시지를 작성하는 방법의 예는 다음과 같습니다.

#! /usr/bin/python

import smtplib

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

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

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

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()


답변

내 메일러 모듈을 사용해보십시오 .

from mailer import Mailer
from mailer import Message

message = Message(From="me@example.com",
                  To="you@example.com")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
   How are you?<br>
   Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

sender = Mailer('smtp.example.com')
sender.send(message)


답변

허용되는 답변 의 Gmail 구현은 다음과 같습니다 .

import smtplib

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

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# 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)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('userName', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()


답변

다음은 Content-Type 헤더를 ‘text / html’로 지정하여 HTML 이메일을 보내는 간단한 방법입니다.

import email.message
import smtplib

msg = email.message.Message()
msg['Subject'] = 'foo'
msg['From'] = 'sender@test.com'
msg['To'] = 'recipient@test.com'
msg.add_header('Content-Type','text/html')
msg.set_payload('Body of <b>message</b>')

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
s.starttls()
s.login(email_login,
        email_passwd)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
s.quit()


답변

샘플 코드는 다음과 같습니다. 이것은 Python Cookbook 사이트 에있는 코드에서 영감을 얻었습니다 (정확한 링크를 찾을 수 없음)

def createhtmlmail (html, text, subject, fromEmail):
    """Create a mime-message that will render HTML in popular
    MUAs, text in better ones"""
    import MimeWriter
    import mimetools
    import cStringIO

    out = cStringIO.StringIO() # output buffer for our message 
    htmlin = cStringIO.StringIO(html)
    txtin = cStringIO.StringIO(text)

    writer = MimeWriter.MimeWriter(out)
    #
    # set up some basic headers... we put subject here
    # because smtplib.sendmail expects it to be in the
    # message body
    #
    writer.addheader("From", fromEmail)
    writer.addheader("Subject", subject)
    writer.addheader("MIME-Version", "1.0")
    #
    # start the multipart section of the message
    # multipart/alternative seems to work better
    # on some MUAs than multipart/mixed
    #
    writer.startmultipartbody("alternative")
    writer.flushheaders()
    #
    # the plain text section
    #
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
    mimetools.encode(txtin, pout, 'quoted-printable')
    txtin.close()
    #
    # start the html subpart of the message
    #
    subpart = writer.nextpart()
    subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
    #
    # returns us a file-ish object we can write to
    #
    pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
    mimetools.encode(htmlin, pout, 'quoted-printable')
    htmlin.close()
    #
    # Now that we're done, close our writer and
    # return the message body
    #
    writer.lastpart()
    msg = out.getvalue()
    out.close()
    print msg
    return msg

if __name__=="__main__":
    import smtplib
    html = 'html version'
    text = 'TEST VERSION'
    subject = "BACKUP REPORT"
    message = createhtmlmail(html, text, subject, 'From Host <sender@host.com>')
    server = smtplib.SMTP("smtp_server_address","smtp_port")
    server.login('username', 'password')
    server.sendmail('sender@host.com', 'target@otherhost.com', message)
    server.quit()


답변

python3의 경우 @taltman의 답변을 개선 하십시오 .

  • 사용하는 email.message.EmailMessage대신 email.message.Message전자 메일을 구성 할 수 있습니다.
  • email.set_contentfunc을 사용 하고 subtype='html'인수를 할당하십시오 . 낮은 수준의 기능 대신 set_payload수동으로 헤더를 추가하십시오.
  • 사용하는 SMTP.send_message대신 FUNC SMTP.sendmail이메일을 보내 FUNC.
  • with연결을 자동으로 닫으 려면 블록을 사용하십시오 .
from email.message import EmailMessage
from smtplib import SMTP

# construct email
email = EmailMessage()
email['Subject'] = 'foo'
email['From'] = 'sender@test.com'
email['To'] = 'recipient@test.com'
email.set_content('<font color="red">red color text</font>', subtype='html')

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.login('foo_user', 'bar_password')
    s.send_message(email)


답변

실제로 yagmail 은 약간 다른 접근 방식을 취했습니다.

그것은 것이다 기본으로 할 수없는 이메일 리더에 대한 자동 대체와 전송 HTML,. 더 이상 17 세기가 아닙니다.

물론 재정의 할 수는 있지만 다음과 같습니다.

import yagmail
yag = yagmail.SMTP("me@example.com", "mypassword")

html_msg = """<p>Hi!<br>
              How are you?<br>
              Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

yag.send("to@example.com", "the subject", html_msg)

설치 지침 및 더 많은 훌륭한 기능에 대해서는 github을 살펴보십시오 .


이 글은 프로그래밍 카테고리에 분류되었고 email, html-email, python 태그가 있으며 [호호] 야야님에 의해 2022년 1월 15일에 작성되었습니다.

글 네비게이션

← Unity 2D가 중단 된 이유는 무엇입니까? 보입니다. 분명히 동일한 일을하기 위해 두 개의 코드베이스를 find 명령을 사용하여 확장자가있는 모든 파일을 목록에서 찾는 방법은 무엇입니까? 파일을 찾아야합니다. find /path/to/ -name “*.jpg” > →

태그

  • android
  • apt
  • backup
  • bash
  • boot
  • c#
  • c++
  • command-line
  • css
  • debian
  • email
  • firefox
  • git
  • google-chrome
  • hard-drive
  • html
  • ios
  • iphone
  • java
  • javascript
  • keyboard
  • linux
  • mac
  • macbook
  • macos
  • microsoft-excel
  • mysql
  • networking
  • performance
  • php
  • python
  • security
  • shell
  • ssh
  • terminal
  • ubuntu
  • unix
  • usb
  • vim
  • virtualbox
  • windows
  • windows-7
  • windows-8
  • windows-10
  • wireless-networking

최신 글

  • 디스크 정리에 많은 시간과 CPU가 필요한 이유는 무엇입니까? 많은 시간을 소비하는 것 같습니다. 파일을
  • Vim에서 일반 모드와 삽입 모드 사이에서 커서를 어떻게 변경합니까? 모양 등)를 변경하는 방법을 알고
  • 집계 대 구성 무엇인지 이해하지만 집계가 무엇인지에 대한 명확한
  • Python 생성기 패턴에 해당하는 C ++
  • 소프트웨어 일반인의 경력 경로는 무엇입니까? [닫은] 전문에 대한 질문 이 질문에 영감을. 소프트웨어 전문가가

카테고리

  • c#
  • c++
  • git
  • html
  • 리눅스
  • 서버
  • 소프트웨어
  • 슈퍼유저
  • 안드로이드
  • 애플
  • 우분투
  • 자바
  • 자바스크립트
  • 파이썬
  • 프로그래밍
apthow.com powered by hoya
Go to mobile version