Вопрос задан 17.02.2019 в 09:32. Предмет Информатика. Спрашивает Ласица Вераника.

Отправка почты с вложением на Python 3, за МАКСИМУМ БАЛОВ БАЛЛОВ!!!!!!! Напишите пожалуйста код на

Python 3 отправляющий (желательно через gmail) письмо с вложением output.txt Заранее спасибо!
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Ильин Вадим.
Функция для отправки емэйлов def send_mail(ваш емэйл, кому вы отравляете, тема письма, содержание письма, файлы вложения 'output.txt' в данном случае) 

Пример использования send_mail("[email protected]", [[email protected]], "Mail", "something", "output.txt") 

Если файл отправлять не нужно, то просто последним параметром можно ничего не указывать, по дефолту стоит отсутствие вложений.

import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

def send_mail(send_from, send_to, subject, text, files=None,
smtplib.SMTP('smtp.gmail.com:587')): 
    assert isinstance(send_to, list)
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject msg.attach(MIMEText(text))

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication( fil.read(), Name=basename(f))  
       part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)    
       msg.attach(part)
     
    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

Sending Email with Attachment in Python 3

To send an email with an attachment using Python 3, you can make use of the `smtplib` and `email` libraries. Here's an example code that sends an email with an attachment named `output.txt` using a Gmail account:

```python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders

def send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, attachment_path): # Create a multipart message object message = MIMEMultipart()

# Set the sender, receiver, subject, and body of the email message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject message.attach(MIMEText(body, "plain"))

# Open the file in bynary with open(attachment_path, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read())

# Encode file in ASCII characters to send by email encoders.encode_base64(part)

# Add header as key/value pair to attachment part part.add_header( "Content-Disposition", f"attachment; filename= {attachment_path}", )

# Add attachment to message and convert message to string message.attach(part) text = message.as_string()

# Connect to the SMTP server and send the email with smtplib.SMTP("smtp.gmail.com", 587) as server: server.starttls() server.login(sender_email, sender_password) server.sendmail(sender_email, receiver_email, text)

# Example usage sender_email = "your_email@gmail.com" sender_password = "your_password" receiver_email = "recipient_email@example.com" subject = "Email with Attachment" body = "Please find the attached file." attachment_path = "output.txt"

send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, attachment_path) ```

Make sure to replace `"your_email@gmail.com"` with your Gmail address, `"your_password"` with your Gmail password, `"recipient_email@example.com"` with the recipient's email address, and `"output.txt"` with the path to the file you want to attach.

Please note that you need to enable "Less Secure Apps" in your Gmail account settings for this code to work. Alternatively, you can use OAuth2 authentication for a more secure approach.

I hope this helps! Let me know if you have any further questions.

0 0

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос