Link to home
Start Free TrialLog in
Avatar of curiouswebster
curiouswebsterFlag for United States of America

asked on

I need an efficient way to email from a C# web service

Can anyone provide the C# code to create and send an email with an HTML body? Also,it would be nice to get a confirmation that it's been sent.

Is there a way to send a batch of emails?  Or is one at a time the only thing possible?

thanks,
newbieweb
Avatar of sabeesh
sabeesh
Flag of United States of America image

Avatar of curiouswebster

ASKER

I am building an object around the code in the link.  Thanks.  But I need to "get inside" the static function called
SendCompletedCallback().  Do you know how I can add my "Email" object as an argument to the function?

   public class SimpleAsynchronousExample
    {
        static bool mailSent = false;
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
             String token = (string) e.UserState;
           
            if (e.Cancelled)
            {
                 Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                 Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            } else
            {
                Console.WriteLine("Message sent.");
            }
            mailSent = true;
        }
SOLUTION
Avatar of William Domenz
William Domenz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
and how to I use an HTML file as the body?
does the SMTP server need to be up and running for the email to go out?
for sending email you need the smtp server, if running exchange, you will need to have the server hosting the service to have privliages to relay the mail
For most of your email needs you can find awesome samples here:
http://www.systemwebmail.com/faq.aspx
can I access that smtp server via an IP address?  Instead of a domain name?

Also, as far as the CallBack function goes...

Does it make sense to send the emails as fast as possible, then accept the call backs when they come? Or should I wait for each callback before going on?
You could try and leverage the call back as an anonymous delegate, I have not tried it myself.

SMTP IPAddress is ok if it is static, else when it changes you will throw an exception.

As fast as possible or not, depends on your resources: server and code.
Does the callback come from the smtp server?  If so it should be fast.  But if it's coming from the domain to which I'm emailing, it will be slow.
the callback is from your relaying SMTP server ... it says *that* server got it ... it does not assure good delivery. I wrote a simple SMTP library which handles "direct" sending to he remote server and can tell you if it actually accepted the email. Some email servers will tll you it suceeds even if it fails for security reasons (like  dictionary attack on emails to determine if they are valid)
I have an error which is stopping me cold.

"The SMTP server requires a secure connection or the client was not authenticated.  The server resonse was: authentication needed."

Where can I input a username and password?   Is that what my SMTP server expects?  I assume I would need the password from my SMTP server?

thanks,
newbieweb


Here is the code...

        public void Send()
        {
            // Command line argument must the the SMTP host.
            SmtpClient client = new SmtpClient(Handles.SMTPServer);
           
            // Specify the e-mail sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.
            MailAddress from = new MailAddress(handles.FromEmail, handles.FromFirstName + " " + /*(char)0xD8+*/ handles.FromLastName, System.Text.Encoding.UTF8);

            // Set destinations for the e-mail message.
            MailAddress to = new MailAddress(this.eMailAddress);
           
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test e-mail message sent by an application. ";
           
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] {'\u2190', '\u2191', '\u2192', '\u2193'});
            message.Body += Environment.NewLine + someArrows;
            message.BodyEncoding =  System.Text.Encoding.UTF8;
            message.Subject = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
           
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
           
            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            Object userState = this;
            client.SendAsync(message, userState);
           
            //Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            //string answer = Console.ReadLine();
           
            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            /*if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }*/

            // Clean up.
            message.Dispose();
            //Console.WriteLine("Goodbye.");
        }


NetworkCredential nc = new NetworkCredential(Username, password); //required by your email server ...
client.UseDefaultCredentials = false;
client.Credentials = nc;
I added the NetworkCredential and validated my username and password.

But now I have "Failure sending mail" as the message.

And I have an InnerException: "Cannot access a disposed object.  Object name: System.New.Mail.MailMesage."

Source=null
StackTrace=null
TargetSize=null

Any ideas?

Bob
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial