It is one of the major requirements in application to inform support team about the errors occurred during production. Or in most of the trading applications, status of the trades needs to be forwarded to the clients through emails [attaching latest reports].
This blog helps users to send emails using a SMTP server which send Outlook emails from a production id rather than from user’s mailbox as generally done by using Microsoft.Office.Interop.Outlook.dll
Here we will use System.Net.Mail instead of Microsoft.Office.Interop.Outlook to send emails. This is done for below advantages:-
1. Mail will be send using a production id instead of current user id
2. This will not use current user’s mailbox and hence in turn will not prompt user to allow accessing his mailbox
3. No need for user’s outlook to be open at the time of sending mail which is a requirement while using Microsoft.Office.Interop.Outlook
a. Include required namespace in the code
b. Create format for email body
c. Create send email method using MailMessage class provided in System.Net.Mail dll. Determine From, To, CC emails id’s either from app.config as done in below example or they can be passed in method also if needs to be dynamic.
d. Call the SendEmail() method whenever required, most generic place is to call in every catch block of the application so that an email is send to the concerned application support group whenever some exception occurs at application level.
Below are the details of above mentioned steps:-
1. Include Namespace in the class
2. Build Message/Email Body
3. App.Config changes [value needs to be modified as per the project]
These values can be directly passed to the SendEmail() method also as per the project requirements
4. Method [Send Mail using SMTP server]
5. Method Call [Send mail when some major exception is encountered in application, ex:- in catch blocks]
6. Output [Mail Body will look like below]
1. Send email in case of some major exception in application has occurred i.e. when main functionality is not working. We can create a method ‘HandleException’ which will call method ‘SendMail’ defined in step 4. ‘HandleException’ method can be called in catch (Exception ex) of try-catch-finally block.
2. BuildMessageBody() method can be modified as per the mail format requirement of the project.
3. Attachments can be added using below code:-
Attachment attach = new Attachment(fileName);
4. Above example shows scenario in which an error has occurred, we can also use this functionality in cases where daily status report needs to be send to the business user.
1. Using SMTP server , one can send mail from a production id
2. It is faster as it does not use user’s outlook to send emails which in turn prompts user to allow accessing his outlook before sending emails.
3. Reduces unnecessary step of allowing access.