I was working on my discord bot trying to implement a email feature where you imbed a file and then the discord bot downloads it and sends it back out to the server. I came across the issue where I have no idea how I would begin to save the file. You can find my code at https://github.com/Omar-Alabdalla/DiscordBot. the specific files that have the emailing feature are mailFunctions(discord commands part) and basicMail(email commands part).
I looked through the docs of nextcord.py and couldn't find any simple way that I could understand. I probably just missed what I was supposed to find though.
discord command Code:
#commands.command()
async def mailFile(self, ctx, *stuff):
# received if else statement from stackoverflow: https://stackoverflow.com/questions/65169339/download-csv-file-sent-by-user-discord-py
if str(ctx.attachments) == "[]": # This checks if there is an attachment on the message
return "You didn't include a file"
else:
await save("mailFile
The mailing class code:
def sendFileMail(rmail, message):
mail_content = '''Hello,
This is a test mail.
In this mail we are sending some attachments.
The mail is sent using Python SMTP library.
Thank You
'''
# Setup the MIME
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = rmail
message['Subject'] = 'A test mail sent by Python. It has an attachment.'
# The subject line
# The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'TP_python_prev.pdf'
attach_file = open(attach_file_name, 'rb') # Open the file as binary mode
payload = MIMEBase('application', 'octate-stream')
payload.set_payload(attach_file.read())
encoders.encode_base64(payload) # encode the attachment
# add payload header with filename
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)
# Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) # use gmail with port
session.starttls() # enable security
session.login(sender_email, password) # login with mail_id and password
text = message.as_string()
session.sendmail(sender_email, rmail, text)
session.quit()
print('Mail Sent')
Apologies for not including code prior First time posting on stack overflow
See Attachment.save: https://nextcord.readthedocs.io/en/latest/api.html?highlight=attachment#nextcord.Attachment.save
for attachment in ctx.message.attachments:
await attachment.save(attachment.filename)
The Gmail API docs states that
Messages and threads can have multiple labels associated with them; however, draft messages cannot have labels applied to them.
However, we can move a draft to inbox using Gmail web UI.
I would like to do the same thing using API. How can this be done?
Thanks to #DalmTo, I found a solution as below.
message = email.mime.text.MIMEText("This is the body")
message['to'] = "to#example.com"
message['from'] = "to#subject.com"
message['subject'] = "Test draft"
payload1 = {"message": {
"raw": base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8"),
# "labelIds": ["INBOX"] # This will cause an error
}}
res1 = google.post("/gmail/v1/users/me/drafts", json=payload1)
payload2 = {"addLabelIds": ["INBOX"], "removeLabelIds":[]}
thread_id = res1.json()["message"]["threadId"]
res2 = google.post(f"/gmail/v1/users/me/threads/{thread_id}/modify", json=payload2)
# Or (both works)
# message_id = res1.json()["message"]["id"]
# res2 = google.post(f"/gmail/v1/users/me/messages/{thread_id}/modify", json=payload2)
I tried sending email using python and put attachment, but when it sent the attachment became noname without any extension.
message = MIMEMultipart()
message ['From'] = sender_email
message ['To'] = ', '.join(receiver_email)
message ['Subject'] = 'Python Email'
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'Final Project - Basic Python.pdf'
attach_file = open('Final Project - Basic Python.pdf', 'rb')
payload = MIMEBase('application', 'octate-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)
I m trying to send emails to my users through my Gmail account but it does not work although my Gmail login credentials are also correct but it gives an error
Here is the code for Email Sending!
if request.method == 'POST':
EmailAddress = request.form['Emails']
Subject = request.form['Subject']
Message = request.form['Message']
EmailList = EmailAddress.split(',')
Message = 'Subject: {}\n\n{}'.format(Subject, Message)
for EmailName in EmailList:
Server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
Server.ehlo()
Server.login(UserEmail, UserPassword)
Server.sendmail(UserEmail, EmailName.strip(), Message)
response = "Success"
Server.quit()
Error:-(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials t21sm2044741ejr.68 - gsmtp')
Anyone please help, I am using sendgrid v3 api. But I cannot find any way to send an email to multiple recipients. Thank in advance.
import sendgrid
from sendgrid.helpers.mail import *
sg = sendgrid.SendGridAPIClient(apikey="SG.xxxxxxxx")
from_email = Email("FROM EMAIL ADDRESS")
to_email = Email("TO EMAIL ADDRESS")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)
I want to send email to multiple recipient. Like to_mail = " xxx#gmail.com, yyy#gmail.com".
Note that with the code of the other answers here, the recipients of the email will see each others emails address in the TO field. To avoid this one has to use a separate Personalization object for every email address:
def SendEmail():
sg = sendgrid.SendGridAPIClient(api_key="YOUR KEY")
from_email = Email ("FROM EMAIL ADDRESS")
person1 = Personalization()
person1.add_to(Email ("EMAIL ADDRESS 1"))
person2 = Personalization()
person2.add_to(Email ("EMAIL ADDRESS 2"))
subject = "EMAIL SUBJECT"
content = Content ("text/plain", "EMAIL BODY")
mail = Mail (from_email, subject, None, content)
mail.add_personalization(person1)
mail.add_personalization(person2)
response = sg.client.mail.send.post (request_body=mail.get())
return response.status_code == 202
You can send an email to multiple recipients by listing them in the to_emails parameter of the Mail constructor:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import *
message = Mail(
from_email='sender#example.com',
to_emails=[To('test#example.com'), To('test2#example.com')],
subject='Subject line',
text_content='This is the message of your email',
)
sg = SendGridAPIClient(SENDGRID_API_KEY)
response = sg.send(message)
With this configuration, each recipient will be able to see each other listed on the email. To avoid this, use the is_multiple parameter to tell Sendgrid to create a new Personalization for each recipient:
message = Mail(
from_email='sender#example.com',
to_emails=[To('test#example.com'), To('test2#example.com')],
subject='Subject line',
text_content='This is the message of your email',
is_multiple=True # Avoid listing all recipients on the email
)
To send email to multiple recicpent in sendgrid v3.
import time
import sendgrid
import os
print "Send email to multiple user"
sg = sendgrid.SendGridAPIClient(apikey='your sendrid key here')
data = {
"personalizations": [
{
"to": [{
"email": "adiii#gmail.com"
}, {
"email": "youremail#gmail.com"
}],
"subject": "Multiple recipent Testing"
}
],
"from": {
"email": "Alert#gmail.com"
},
"content": [
{
"type": "text/html",
"value": "<h3 style=\"color: #ff0000;\">These checks are silenced please check dashboard. Click HERE</h3> <br><br> <h3>For any query please contact DevOps Team<h3>"
}
]
}
response = sg.client.mail.send.post(request_body=data)
print(response.status_code)
if response.status_code == 202:
print "email sent"
else:
print("Checking body",response.body)
https://libraries.io/github/sendwithus/sendgrid-python
You can update your code in the below way. You can find the same in mail_example.py present in Sendgrid's package.
personalization = get_mock_personalization_dict()
mail.add_personalization(build_personalization(personalization))
def get_mock_personalization_dict():
"""Get a dict of personalization mock."""
mock_pers = dict()
mock_pers['to_list'] = [Email("test1#example.com",
"Example User"),
Email("test2#example.com",
"Example User")]
return mock_pers
def build_personalization(personalization):
"""Build personalization mock instance from a mock dict"""
mock_personalization = Personalization()
for to_addr in personalization['to_list']:
mock_personalization.add_to(to_addr)
return mock_personalization
Based on Subhrajyoti Das answer, I wrote the following code, that is a simpler version of the mail_example.py example of sending email to multiple recipient.
def SendEmail():
sg = sendgrid.SendGridAPIClient(api_key="YOUR KEY")
from_email = Email ("FROM EMAIL ADDRESS")
to_list = Personalization()
to_list.add_to (Email ("EMAIL ADDRESS 1"))
to_list.add_to (Email ("EMAIL ADDRESS 2"))
to_list.add_to (Email ("EMAIL ADDRESS 3"))
subject = "EMAIL SUBJECT"
content = Content ("text/plain", "EMAIL BODY")
mail = Mail (from_email, None, subject, content)
mail.add_personalization (to_list)
response = sg.client.mail.send.post (request_body=mail.get())
return response.status_code == 202
You can pass a list of strings.
message = Mail(
from_email='sender#email.com',
to_emails=['xxx#email.com', 'yyy#email.com'],
subject='subject',
html_content='content')
sg = SendGridAPIClient('SENDGRID_API_KEY')
response = sg.send(message)