python smtplib을 사용하여 여러 수신자에게 이메일을 보내는 방법은 무엇입니까?
많은 검색을 한 후 smtplib.sendmail을 사용하여 여러 수신자에게 보내는 방법을 찾을 수 없었습니다. 문제는 메일을 보낼 때마다 메일 헤더에 여러 주소가 포함 된 것처럼 보이지만 실제로는 첫 번째 수신자 만 전자 메일을받습니다.
문제는 email.Message
모듈이 smtplib.sendmail()
기능 과 다른 것을 기대 하는 것 같습니다 .
즉, 여러 수신자에게 보내려면 헤더를 쉼표로 구분 된 전자 메일 주소 문자열로 설정해야합니다. sendmail()
매개 변수는 to_addrs
그러나 이메일 주소의 목록이어야합니다.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me@example.com"
msg["To"] = "malcom@example.com,reynolds@example.com,firefly@example.com"
msg["Cc"] = "serenity@example.com,inara@example.com"
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
smtp.quit()
이것은 실제로 작동합니다 . 여러 변형을 시도하는 데 많은 시간을 보냈습니다.
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())
은 msg['To']
문자열이어야합니다 :
msg['To'] = "a@b.com, b@b.com, c@b.com"
recipients
in sendmail(sender, recipients, message)
은 목록이어야 하지만 :
sendmail("a@a.com", ["a@b.com", "b@b.com", "c@b.com"], "Howdy")
이메일 의 보이는 주소와 배달 의 차이점을 이해해야합니다 .
msg["To"]
본질적으로 편지에 인쇄되어 있습니다. 실제로 아무런 영향을 미치지 않습니다. 전자 우편 클라이언트는 정규 우체국과 마찬가지로 전자 우편을 보낼 사람이라고 가정합니다.
그러나 실제 배송은 상당히 다를 수 있습니다. 따라서 이메일 (또는 사본)을 완전히 다른 사람의 포스트 박스에 놓을 수 있습니다 .
여기에는 여러 가지 이유가 있습니다. 예를 들어 전달 . To:
헤더 필드가 전달에 변경되지 않습니다, 그러나 이메일은 다른 사서함으로 삭제됩니다.
이 smtp.sendmail
명령은 이제 실제 배달을 처리합니다. email.Message
배달 내용이 아닌 문자의 내용입니다.
하위 수준 SMTP
에서는 수신자에게 하나씩 하나씩 제공해야하므로 주소 목록 (이름 제외)이 합리적인 API입니다.
헤더의 경우 예를 들어 이름을 포함 할 수도 있습니다 To: First Last <email@addr.tld>, Other User <other@mail.tld>
. 따라서 코드를 분할해도 ,
유효한 주소가 없기 때문에이 메일 전달에 실패 하므로 코드 예제는 권장 되지 않습니다!
그것은 나를 위해 작동합니다.
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = 'john.doe@example.com,john.smith@example.co.uk'
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = recipients
s.sendmail(sender, recipients.split(','), msg.as_string())
나는 아래를 시도했고 그것은 매력처럼 일했다 :)
rec_list = ['first@example.com', 'second@example.com']
rec = ', '.join(rec_list)
msg['To'] = rec
send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())
실제로 문제는 SMTP.sendmail과 email.MIMEText가 두 가지 다른 것이 필요하다는 것입니다.
email.MIMEText sets up the "To:" header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)
SMTP.sendmail, on the other hand, sets up the "envelope" of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.
So, what you need to do is COMBINE the two replies you received. Set msg['To'] to a single string, but pass the raw list to sendmail:
emails = ['a.com','b.com', 'c.com']
msg['To'] = ', '.join( emails )
....
s.sendmail( msg['From'], emails, msg.as_string())
I came up with this importable module function. It uses the gmail email server in this example. Its split into header and message so you can clearly see whats going on:
import smtplib
def send_alert(subject=""):
to = ['email@one.com', 'email2@another_email.com', 'a3rd@email.com']
gmail_user = 'me@gmail.com'
gmail_pwd = 'my_pass'
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + ", ".join(to) + '\n' + 'From: ' + gmail_user + '\n' + 'Subject: ' + subject + '\n'
msg = header + '\n' + subject + '\n\n'
smtpserver.sendmail(gmail_user, to, msg)
smtpserver.close()
I figured this out a few months back and blogged about it. The summary is:
If you want to use smtplib to send email to multiple recipients, use email.Message.add_header('To', eachRecipientAsString)
to add them, and then when you invoke the sendmail method, use email.Message.get_all('To')
send the message to all of them. Ditto for Cc and Bcc recipients.
The solution below worked for me. It successfully sends an email to multiple recipients, including "CC" and "BCC."
toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n !! Hello... !!"
msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject
s.sendmail(fromaddr, (toaddr+cc+bcc) , message)
Well, the method in this asnwer method did not work for me. I don't know, maybe this is a Python3 (I am using the 3.4 version) or gmail related issue, but after some tries, the solution that worked for me, was the line
s.send_message(msg)
instead of
s.sendmail(sender, recipients, msg.as_string())
I use python 3.6 and the following code works for me
email_send = 'xxxxx@xxx.xxx,xxxx@xxx.xxx'
server.sendmail(email_user,email_send.split(','),text)
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sender(recipients):
body = 'Your email content here'
msg = MIMEMultipart()
msg['Subject'] = 'Email Subject'
msg['From'] = 'your.email@gmail.com'
msg['To'] = (', ').join(recipients.split(','))
msg.attach(MIMEText(body,'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('your.email@gmail.com', 'yourpassword')
server.send_message(msg)
server.quit()
if __name__ == '__main__':
sender('email_1@domain.com,email_2@domain.com')
It only worked for me with send_message function and using the join function in the list whith recipients, python 3.6.
you can try this when you write the recpient emails on a text file
from email.mime.text import MIMEText
from email.header import Header
import smtplib
f = open('emails.txt', 'r').readlines()
for n in f:
emails = n.rstrip()
server = smtplib.SMTP('smtp.uk.xensource.com')
server.ehlo()
server.starttls()
body = "Test Email"
subject = "Test"
from = "me@example.com"
to = emails
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
text = msg.as_string()
try:
server.send(from, emails, text)
print('Message Sent Succesfully')
except:
print('There Was An Error While Sending The Message')
'Programing' 카테고리의 다른 글
Vim이 ~ 확장자를 가진 파일을 저장하는 이유는 무엇입니까? (0) | 2020.05.25 |
---|---|
UIImage를 NSData로 변환 (0) | 2020.05.25 |
Node.js는 폴더를 만들거나 기존 폴더를 사용합니다 (0) | 2020.05.25 |
Ruby on Rails 3 양식의 _snowman 매개 변수는 무엇입니까? (0) | 2020.05.24 |
Visual Studio에서 결과 찾기를 클릭하면 잘못된 창에서 코드가 열립니다. (0) | 2020.05.24 |