سؤال

أنا أستخدم الطريقة التالية لإرسال البريد من Python باستخدام SMTP.هل هي الطريقة الصحيحة للاستخدام أم أن هناك أخطاء أفتقدها؟

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؛لذلك يمكن تعديل هذا البرنامج النصي بسهولة لإرفاق الصور وما إلى ذلك.

أعتمد على مزود خدمة الإنترنت الخاص بي لإضافة رأس التاريخ والوقت.

يطلب مني مزود خدمة الإنترنت الخاص بي استخدام اتصال 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()

هذا كل شيء

وأيضًا إذا كنت تريد إجراء مصادقة smtp باستخدام TLS بدلاً من SSL، فما عليك سوى تغيير المنفذ (استخدم 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)))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top