# How to send an email to user with custom action

**URL:** <https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117>\
**Category:** Rasa Open Source\
**Created:** [December 5, 2019, 4:20pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117 "2019-12-05T16:20:23Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [December 5, 2019, 4:20pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/1 "2019-12-05T16:20:23Z")

</div>

I unable to send email to user after getting email id from the user response

action.py

class ActionSendEmail(Action): def name(self): return “action\_send\_email” # add this to the actions in domain.yml file # this is the name of your custom action

```
def run(self, dispatcher, tracker, domain):
	# trackers gives us the stored email_id slot done by intents
	# change the slot name as per your requirements and get it using the below code.
	email_id = tracker.get_slot('email_id')
	# this message will be sent to the UI.
	return f"Confirmation email is sent to {email_id}"

```

can any one help me Thank you.

---

<div class="post-metadata">

**Author:** ![stephens](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/stephens/32/1632_2.png) [@stephens](https://forum.rasa.com/u/stephens)\
**Post date:** [December 6, 2019, 8:28pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/2 "2019-12-06T20:28:34Z")

</div>

You’ll need to setup an email service or use a mail server of your own. You can see a complete example email send action using MailChimp in our Sara bot [here](https://github.com/RasaHQ/rasa-demo/blob/6212face2a6b5fd36b0726e43df018c76ef2279a/demo/actions.py#L48).

---

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [December 6, 2019, 9:19pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/3 "2019-12-06T21:19:38Z")

</div>

thanks for your help.

i have a doubt . conversation : User:- hi bot: Hi I am karthik. How may i help you user:- I want to know about your solutions. bot:- Can you please send me you mail id. user:- [karthik@gmail.com](mailto:karthik@gmail.com)

Here users as given mail id after that bot has to send a default email like Welcome to XXX company and product details.

So is it possible in this way. Please guide me.

---

<div class="post-metadata">

**Author:** ![stephens](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/stephens/32/1632_2.png) [@stephens](https://forum.rasa.com/u/stephens)\
**Post date:** [December 6, 2019, 9:55pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/4 "2019-12-06T21:55:19Z")

</div>

Yes, you should read about Forms in this forum [post](https://blog.rasa.com/building-contextual-assistants-with-rasa-formaction/) and our [docs](https://rasa.com/docs/rasa/core/forms/).

---

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [December 9, 2019, 6:55pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/5 "2019-12-09T18:55:15Z")

</div>

Hi, Sorry for delay.

by using the forms action how can i send the default mails to users please guide me more. If you have any sample code please send me

---

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [December 10, 2019, 4:00pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/6 "2019-12-10T16:00:25Z")

</div>

hi MailChimp is not free for every one please tell me

---

<div class="post-metadata">

**Author:** ![stephens](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/stephens/32/1632_2.png) [@stephens](https://forum.rasa.com/u/stephens)\
**Post date:** [December 11, 2019, 3:15pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/7 "2019-12-11T15:15:17Z")

</div>

I can’t speak for Mailchimp or the other mail services. I think they have a free tier but I don’t know the details. Rasa doesn’t include an mail server.

---

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [December 11, 2019, 3:44pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/9 "2019-12-11T15:44:31Z")

</div>

Thank you for your information. So is there any way to send a default mail to senders

please guide me

actions.py import logging from datetime import datetime from typing import Text, Dict, Any, List import json

from rasa\_sdk import Action, Tracker from rasa\_sdk.executor import CollectingDispatcher from rasa\_sdk.forms import FormAction from rasa\_sdk.events import SlotSet, UserUtteranceReverted, ConversationPaused

import requests class ActionStoreEmail(Action): “”“Stores the email in a slot”""

```auto
def name(self):
	return "action_store_email"

def run(self, dispatcher, tracker, domain):
	email = next(tracker.get_latest_entity_values('email'), None)

    # if no email entity was recognised, prompt the user to enter a valid
    # email and go back a turn in the conversation to ensure future
    # predictions aren't affected
	if not email:
		email = tracker.latest_message.get('text')
		dispatcher.utter_message("We need your email, "
                                 "please enter a valid one.")
		return [UserUtteranceReverted()]

	return [SlotSet('email', email)]     

```

class sendmail(FormAction): def name(self): return “action\_sendmail”

```auto
@staticmethod
def required_slots(tracker):
    return ["email"]

def slot_mappings(self):
    return {
        "email": [
            self.from_entity(entity="email"),
            self.from_text(intent="enter_data"),
        ]
    }

def validate_email(self, value, dispatcher, tracker, domain):
    """Check to see if an email entity was actually picked up by duckling."""

    if any(tracker.get_latest_entity_values("email")):
        # entity was picked up, validate slot
        return {"email": value}
    else:
        # no entity was picked up, we want to ask again
        dispatcher.utter_template("utter_no_email", tracker)
        return {"email": None}

def submit(
    self,
    dispatcher: CollectingDispatcher,
    tracker: Tracker,
    domain: Dict[Text, Any],
) -> List[Dict]:
    """Once we have an email, attempt to add it to the database"""

    email = tracker.get_slot("email")
    client = MailChimpAPI(config.mailchimp_api_key)
    # if the email is already subscribed, this returns False
    added_to_list = client.subscribe_user(config.mailchimp_list, email)
     
     
    # utter submit template
    if added_to_list:
        dispatcher.utter_template("utter_confirmationemail", tracker)
    else:
        dispatcher.utter_template("utter_already_subscribed", tracker)
        
    
    

def run(self, dispatcher, tracker,domain):
    import requests
    from email.message import EmailMessage
    
    From= tracker.get_slot("From")
    To= tracker.get_slot("email")
    User= tracker.get_slot("name")
    
    msg= EmailMessage()
    msg['Subject']= ("Thank You For Your visit ")
    msg[To]= 'receving_email_address'
    
    msg.set_content("Hi,/n I am Alisa from ")
    response = unirest.post("https://OutlookMailstefan-skliarovV1.p.rapidapi.com/sendMessage",
      headers={
      "X-RapidAPI-Host": "OutlookMailstefan-skliarovV1.p.rapidapi.com",
      "X-RapidAPI-Key": "4f0e828645msh38bfffaf5438379p18ee2bjsn93ce93b0cd4f",
      "Content-Type": "application/x-www-form-urlencoded"

```

} )

```auto
    return []

```

i have written code like above , but the problem here is now bot prediction was wrong.

---

<div class="post-metadata">

**Author:** ![stephens](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/stephens/32/1632_2.png) [@stephens](https://forum.rasa.com/u/stephens)\
**Post date:** [December 12, 2019, 10:45pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/10 "2019-12-12T22:45:00Z")

</div>

> So is there any way to send a default mail to senders

I’m not sure I follow your question but I think you’re asking how to send an email with Python. Either way, sending email is not an inherent feature of Rasa, it would be something you would do in a Python action using whatever modules and mail services you choose.

> the problem here is now bot prediction was wrong

I think you’re saying that the `email` entity was not extracted from an intent. Is that correct? If so, please paste your intent examples here.

---

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [December 12, 2019, 11:41pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/12 "2019-12-12T23:41:12Z")

</div>

Thank you for your help

Chatbot is working fine. Issue resolved.

So Rasa did not have a module to send a default mail to a user. In action.py file I have written the mail configuration but it is not working. can you help on this.

My Bot is for marketing so when user ask about company product, it will give brief introduction. So in this process bot will ask user details. So user will give mail id after that bot as to send an email to user about our products after conversation.

---

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [December 13, 2019, 5:27pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/13 "2019-12-13T17:27:01Z")

</div>

action.py

class MailForm(FormAction):

```
def name(self):
    return "Send_MailtoUser"
    
@staticmethod
def required_slots(tracker : Tracker) -> List[Text]:
    return ["name", "email"]

def slot_mappings(self):
    
    return {"name": [self.from_entity(entity="name"),self.from_text()],
            "email": [self.from_entity(entity="email"), self.from_text(intent="enter_data")]}
            
            

def validate_email(self, value, dispatcher, tracker, domain):
    """Check to see if an email entity was actually picked up by duckling."""

    if any(tracker.get_latest_entity_values("email")):
        # entity was picked up, validate slot
        return {"email": value}
    else:
        # no entity was picked up, we want to ask again
        dispatcher.utter_template("utter_no_email", tracker)
        return {"email": None}
        
def submit(self,
           dispatcher: CollectingDispatcher,
           tracker: Tracker,
           domain: Dict[Text, Any]) -> List[Dict]:
    """Define what the form has to do
        after all required slots are filled"""

    # utter submit template
    dispatcher.utter_template('utter_submit', tracker)
    return []

```

class DefaultMail(Action): def name(self): return(“action\_Default\_Mail”)

```
def run(self, dispatcher, tracker, domain):
    import os
    import email, smtplib, ssl
    from email.mime.base import MIMEBase
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    
    subject = "Thank you for visiting Lanconic.com"
    
    body = "Hello.. For more details please visit our website"
       
    sender_email = "karthik@lanconic.com"
    receiver_email = tracker.get_slot("email")
    password = xyx
    
    
    # Create a multipart message and set headers
    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = receiver_email
    message["Subject"] = subject
    
    # Add body to email
    message.attach(MIMEText(body, "plain"))
    
    filename = "apigateway-dg.pdf" # In same directory as script
    
    # Open PDF file in binary mode
    with open(filename, "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= {filename}",
        )
    
        # Add attachment to message and convert message to string
        message.attach(part)
        text = message.as_string()
    
        # Log in to server using secure context and send email
        context = ssl.create_default_context()
        s = smtplib.SMTP(host='smtp.office365.com', port=587)
        s.starttls()
        s.login(sender_email, password)
        s.sendmail(sender_email, receiver_email, message.as_string())
        
        return[]

```

this code working when we run as rasa run actions but when we use with model not working the custom action.

---

<div class="post-metadata">

**Author:** ![stephens](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/stephens/32/1632_2.png) [@stephens](https://forum.rasa.com/u/stephens)\
**Post date:** [December 15, 2019, 3:13am UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/14 "2019-12-15T03:13:18Z")

</div>

We have a complete working example that collects a users email address and sends them an email in our [rasa-demo](https://github.com/RasaHQ/rasa-demo).

You should review the intent, stories and code related to the email intent. You can clone this to your system. Replace mailchimp with the mailing service of your choice.

Review the logs to determine if your actions are being called as you expect them to.

---

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [December 16, 2019, 7:32pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/17 "2019-12-16T19:32:49Z")

</div>

actions.py class MailForm(FormAction):

```auto
def name(self):
    return "Send_MailtoUser"
    
@staticmethod
def required_slots(tracker : Tracker) -> List[Text]:
    return ["email"]

def slot_mappings(self):
    return {
        "email": [
            self.from_entity(entity="email"),
            self.from_text(intent="enter_data"),
        ]
    }          
            

def validate_email(self, value, dispatcher, tracker, domain):
    """Check to see if an email entity was actually picked up by duckling."""

    if any(tracker.get_latest_entity_values("email")):
        # entity was picked up, validate slot
        return {"email": value}
    else:
        # no entity was picked up, we want to ask again
        dispatcher.utter_template("utter_no_email", tracker)
        return {"email": None}
        
def submit(self,
    dispatcher: CollectingDispatcher,
    tracker: Tracker,
    domain: Dict[Text, Any]) -> List[Dict]:
           
      
    email = tracker.get_slot("email")
           
           # utter submit template
    dispatcher.utter_template('utter_submit', tracker)
           
 
def run(self, dispatcher, tracker, domain):
    email = next(tracker.get_latest_entity_values('email'), None)  
    email = tracker.get_slot("email")
    os.chdir("C:\\Users\\karthik\\Desktop")

    subject = "Thank you for visiting Lanconic.com"
  
    body = "Hello.. \n\n Greetings from Lanconic.!! \n\n Thank You for your enquiry.\n\n Based on our Conversation I have found the following Content which would help you further. \n 1. Smart Recruit. \n 2. Employee Time Sheet Management. \n 3. CareerFetch. \n 4. Our Award Winning - Workforce Capital Management Solution. \n\n Hope to See you again.\n\n Bye.\n \n Best Regards \n Alisa. \n \n For more details please visit our website – www.lanconic.com"
       
    sender_email = 
    email = [tracker.get_slot("email")]
    password = "
    
    
     # Create a multipart message and set headers
    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = email
    message["Subject"] = subject
    
             # Add body to email
    message.attach(MIMEText(body, "plain"))
    
    filename = "apigateway-dg.pdf" # In same directory as script
    
            # Open PDF file in binary mode
    with open(filename, "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= {filename}",
    )
    
         # Add attachment to message and convert message to string
    message.attach(part)
    text = message.as_string()
    
            # Log in to server using secure context and send email
    context = ssl.create_default_context()
    s = smtplib.SMTP(host='smtp.office365.com', port=587)
    s.starttls()
    s.login(sender_email, password)
    s.sendmail(sender_email, email, message.as_string())
    return[]    

```

after user entering the email i am getting error

2019-12-17 00:54:50 ERROR rasa.core.processor - Encountered an exception while running action ‘Send\_MailtoUser’. Bot will continue, but the actions events are lost. Please check the logs of your action server for more information. 2019-12-17 00:54:50 DEBUG rasa.core.processor - Failed to execute custom action. Traceback (most recent call last): File “c:\users\karthik\appdata\local\continuum\anaconda3\envs\rasabot\lib\site-packages\rasa\core\actions\action.py”, line 451, in run json=json\_body, method=“post”, timeout=DEFAULT\_REQUEST\_TIMEOUT File “c:\users\karthik\appdata\local\continuum\anaconda3\envs\rasabot\lib\site-packages\rasa\utils\endpoints.py”, line 148, in request resp.status, resp.reason, await resp.content.read() rasa.utils.endpoints.ClientResponseError: 500, Internal Server Error, body=‘b’\n

please help me regarding this issue

---

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [March 5, 2020, 9:59pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/18 "2020-03-05T21:59:10Z")

</div>

sorry for late issue got resolve

---

<div class="post-metadata">

**Author:** ![sid321axn](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/sid321axn/32/12494_2.png) [@sid321axn](https://forum.rasa.com/u/sid321axn)\
**Post date:** [April 25, 2020, 12:57pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/19 "2020-04-25T12:57:43Z")

</div>

how the issue resolved actually i m also facing the same issue i have build a restaurant search chatbot which asks users email address for send restraunt details its working fine on local server but after deploying on slack mail is not getting sent and even email is not recognizing as an entity

---

<div class="post-metadata">

**Author:** ![karthik1](https://avatars.discourse-cdn.com/v4/letter/k/bc8723/32.png) [@karthik1](https://forum.rasa.com/u/karthik1)\
**Post date:** [April 27, 2020, 8:25pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/20 "2020-04-27T20:25:38Z")

</div>

hi May i know your deployment process

---

<div class="post-metadata">

**Author:** ![Akhil1278](https://avatars.discourse-cdn.com/v4/letter/a/58f4c7/32.png) [@Akhil1278](https://forum.rasa.com/u/Akhil1278)\
**Post date:** [May 27, 2020, 9:47am UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/21 "2020-05-27T09:47:26Z")

</div>

I have similar doubt can youhelp me

---

<div class="post-metadata">

**Author:** ![Pavankumar](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/pavankumar/32/9526_2.png) [@Pavankumar](https://forum.rasa.com/u/Pavankumar)\
**Post date:** [June 9, 2020, 3:08pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/22 "2020-06-09T15:08:23Z")

</div>

hi iam new for rasa can anyone please tell me how to communicate to mail

---

<div class="post-metadata">

**Author:** ![Youssef-0](https://avatars.discourse-cdn.com/v4/letter/y/a6a055/32.png) [@Youssef-0](https://forum.rasa.com/u/Youssef-0)\
**Post date:** [June 11, 2020, 2:13pm UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/24 "2020-06-11T14:13:58Z")

</div>

> [Sending email through action](http://forum.rasa.com/t/sending-email-through-action/28328)

---

<div class="post-metadata">

**Author:** ![vishal4000](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/vishal4000/32/11814_2.png) [@vishal4000](https://forum.rasa.com/u/vishal4000)\
**Post date:** [November 8, 2020, 3:26am UTC](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117/25 "2020-11-08T03:26:29Z")

</div>

Can anyone provide sample chatbot code to send user inputted data through email

[Next page](https://forum.rasa.com/t/how-to-send-an-email-to-user-with-custom-action/22117.md?page=2)
