Click here to Skip to main content

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#, VB.NET

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.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).



Advertise | Privacy | Mobile
Web02 | 2.8.141223.1 | Last Updated 26 Mar 2009
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100