Click here to Skip to main content
15,881,812 members

Sending Emails from Desktop Application

mhamad zarif asked:

Open original thread
Hi all ,

I developed a desktop sending email application,but it is generating an error when sending and the exception is saying : failure in sending mail.So is is a problem from the code or from my smtp server.?please help me,and this is my code down.

<pre lang="xml">using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Text.RegularExpressions;
using System.Web;

namespace EmailHandler
{
    public class Emailer
    {
        /// <summary>
        /// Transmit an email message to a recipient without
        /// any attachments
        /// </summary>
        /// <param name="sendTo">Recipient Email Address</param>
        /// <param name="sendFrom">Sender Email Address</param>
        /// <param name="sendSubject">Subject Line Describing Message</param>
        /// <param name="sendMessage">The Email Message Body</param>
        /// <returns>Status Message as String</returns>
        public static string SendMessage(string sendTo, string sendFrom,
            string sendSubject, string sendMessage)
        {
            try
            {
                // validate the email address
                bool bTest = ValidateEmailAddress(sendTo);
                // if the email address is bad, return message
                if (bTest == false)
                    return "Invalid recipient email address: " + sendTo;
                // create the email message
                MailMessage message = new MailMessage(
                   sendFrom,
                   sendTo,
                   sendSubject,
                   sendMessage);
                // create smtp client at mail server location
                SmtpClient client = new SmtpClient(Properties.Settings.Default.SMTPAddress);
                // add credentials
                client.UseDefaultCredentials = true;
                // send message
                client.Send(message);
                return "Message sent to " + sendTo + " at " + DateTime.Now.ToString() + ".";
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

        /// <summary>
        /// Transmit an email message with
        /// attachments
        /// </summary>
        /// <param name="sendTo">Recipient Email Address</param>
        /// <param name="sendFrom">Sender Email Address</param>
        /// <param name="sendSubject">Subject Line Describing Message</param>
        /// <param name="sendMessage">The Email Message Body</param>
        /// <param name="attachments">A string array pointing to the location of each attachment</param>
        /// <returns>Status Message as String</returns>
        public static string SendMessageWithAttachment(string sendTo, string sendFrom,
            string sendSubject, string sendMessage, ArrayList attachments)
        {
            try
            {
                // validate email address
                bool bTest = ValidateEmailAddress(sendTo);
                if (bTest == false)
                    return "Invalid recipient email address: " + sendTo;
                // Create the basic message
                MailMessage message = new MailMessage(
                   sendFrom,
                   sendTo,
                   sendSubject,
                   sendMessage);
                // The attachments arraylist should point to a file location where
                // the attachment resides - add the attachments to the message
                foreach (string attach in attachments)
                {
                    Attachment attached = new Attachment(attach, MediaTypeNames.Application.Octet);
                    message.Attachments.Add(attached);
                }
                // create smtp client at mail server location
                SmtpClient client = new SmtpClient(Properties.Settings.Default.SMTPAddress);
                client.EnableSsl = true;
                // Add credentials
                client.UseDefaultCredentials = true;
                // send message
                client.Send(message);
                return "Message sent to " + sendTo + " at " + DateTime.Now.ToString() + ".";
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

        /// <summary>
        /// Confirm that an email address is valid
        /// in format
        /// </summary>
        /// <param name="emailAddress">Full email address to validate</param>
        /// <returns>True if email address is valid</returns>
        public static bool ValidateEmailAddress(string emailAddress)
        {
            try
            {
                string TextToValidate = emailAddress;
                Regex expression = new Regex(@"\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}");
                // test email address with expression
                if (expression.IsMatch(TextToValidate))
                {
                    // is valid email address
                    return true;
                }
                else
                {
                    // is not valid email address
                    return false;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}


<pre lang="xml">using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EmailHandler;

namespace EmailTestApp
{
    /// <summary>
    /// Test Application Form:
    /// This application is used to test sending
    /// email and email with attachments.
    /// </summary>
    public partial class frmTestEmail : Form
    {
        /// <summary>
        /// An arraylist containing
        /// all of the attachments
        /// </summary>
        ArrayList alAttachments;

        /// <summary>
        /// Default constructor
        /// </summary>
        public frmTestEmail()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Add files to be attached to the email message
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string[] arr = openFileDialog1.FileNames;
                    alAttachments = new ArrayList();
                    txtAttachments.Text = string.Empty;
                    alAttachments.AddRange(arr);
                    foreach (string s in alAttachments)
                    {
                        txtAttachments.Text += s + "; ";
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                }
            }
        }

        /// <summary>
        /// Exit the application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// Send an email message with or without attachments
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtSendTo.Text))
            {
                MessageBox.Show("Missing recipient address.", "Email Error");
                return;
            }
            if (String.IsNullOrEmpty(txtSendFrom.Text))
            {
                MessageBox.Show("Missing sender address.", "Email Error");
                return;
            }
            if (String.IsNullOrEmpty(txtSubjectLine.Text))
            {
                MessageBox.Show("Missing subject line.", "Email Error");
                return;
            }
            if (String.IsNullOrEmpty(txtMessage.Text))
            {
                MessageBox.Show("Missing message.", "Email Error");
                return;
            }
            string[] arr = txtAttachments.Text.Split(';');
            alAttachments = new ArrayList();
            for (int i = 0; i < arr.Length; i++)
            {
                if (!String.IsNullOrEmpty(arr[i].ToString().Trim()))
                {
                    alAttachments.Add(arr[i].ToString().Trim());
                }
            }
            // if there are attachments, send message with
            // SendMessageWithAttachment call, else use the
            // standard SendMessage call
            if (alAttachments.Count > 0)
            {
                string result = Emailer.SendMessageWithAttachment(txtSendTo.Text,
                    txtSendFrom.Text, txtSubjectLine.Text, txtMessage.Text,
                    alAttachments);
                MessageBox.Show(result, "Email Transmittal");
            }
            else
            {
                string result = Emailer.SendMessage(txtSendTo.Text,
                    txtSendFrom.Text, txtSubjectLine.Text, txtMessage.Text);
                MessageBox.Show(result, "Email Transmittal");
            }
        }

    }
}

Tags: C#, Visual Basic

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900