Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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");
            }
        }

    }
}

Posted

The best thing you can do is to look at the actual exception: it should give you more info, particularly in the inner exception. Either put breakpoints in each catch block to see what is going on, or use "Debug...Exceptions" from the menu and tick everything in the "Thrown" column to catch every exception, whether handled or not.
 
Share this answer
 
Comments
Espen Harlinn 25-Feb-11 11:07am    
Good advice, my 5
Use Gmail smtp server for testing its free
smtp.gmail.com port:587 and use your gmail user name and password instead of default and set ssl true.

because its seems problem with your smtp server

--Pankaj
 
Share this answer
 
Comments
mhamad zarif 25-Feb-11 14:53pm    
Hi Pankaj,i followed what you said but it is still not working and those are my modifications :

SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;

// Add credentials
client.Credentials = new System.Net.NetworkCredential("ahmad.bastas@gmail.com", "parking11");
client.UseDefaultCredentials = false;
Hello,
You can use this code to send email to from all mail servers

Best Regards
Morteza Shoja

_______________________________________
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
_______________________________________
Private Sub EmailSender(ByVal From As String, ByVal DisplayName As String, ByVal SendTo As String, ByVal Message As String, ByVal Subject As String, ByVal Password As String, ByVal Attach As String)
 Using mailMessage As New MailMessage(New MailAddress(SendTo), New MailAddress(SendTo))
 mailMessage.Body = Message
 mailMessage.Subject = Subject
 Try
 Dim SmtpServer As New SmtpClient()
 SmtpServer.Credentials = New System.Net.NetworkCredential(From, Password)
 SmtpServer.Port = 587

 Dim MS() As String = From.ToString.Split("@")
 Dim MailServer() As String = MS(1).ToString.Split(".")
 Select Case UCase(MailServer(0))
 Case Is = "GMAIL"
 SmtpServer.Host = "smtp.gmail.com"
 SmtpServer.EnableSsl = True
 Case Is = "YAHOO"
 SmtpServer.Host = "smtp.mail.yahoo.com"
 SmtpServer.EnableSsl = False
 Case Is = "AOL"
 SmtpServer.Host = "smtp.aol.com"
 SmtpServer.EnableSsl = False
 Case Is = "LIVE"
 SmtpServer.Credentials = New System.Net.NetworkCredential(From, Password)
 SmtpServer.Host = "smtp.live.com"
 SmtpServer.EnableSsl = True
 End Select

 mail = New MailMessage()
 Dim addr() As String = SendTo.Split(",")
 mail.From = New MailAddress(From, DisplayName, System.Text.Encoding.UTF8)
 Dim i As Byte
 For i = 0 To addr.Length - 1
 mail.To.Add(addr(i))
 Next i
 mail.Subject = Subject
 mail.Body = Message
 mail.BodyEncoding = System.Text.Encoding.UTF7
 If Attach.Length <> 0 Then
 mail.Attachments.Add(New Attachment(Attach))
 End If
 mail.IsBodyHtml = True
 mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
 mail.ReplyTo = New MailAddress(SendTo)
 SmtpServer.Send(mail)
 Catch ex As Exception
 MessageBox.Show(ex.Message, "EMail", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
 End Try
 End Using
 End Sub
 
Share this answer
 
v2
So is is a problem from the code or from my smtp server?

Well, you are almost there. You are using the default credentials, I would start looking up from there.
 
Share this answer
 
Try:
1. Check if the port used is open.
2. Check if Firewall permissions are in place.
3. Check if proper security permissions are set on SMTP server and username/password used are working
 
Share this answer
 
Comments
mhamad zarif 25-Feb-11 10:23am    
Thanks for your help Sandeep.But please iam a beginner and i dont know how to know how to check the proper security permissions in smtp and firewall permissions.Please help me,iam using windows 7.please help me,i need to solve this problem as fast as i can.Thanks in advance.
Sandeep Mewara 25-Feb-11 10:28am    
Talk to your IT team.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



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