?
Solved

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

Posted on 2007-08-08
15
Medium Priority
?
194 Views
Last Modified: 2013-12-17
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
0
Comment
Question by:newbieweb
  • 7
  • 4
  • 3
  • +1
15 Comments
 
LVL 8

Expert Comment

by:sabeesh
ID: 19659177
0
 

Author Comment

by:newbieweb
ID: 19659394
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;
        }
0
 
LVL 11

Assisted Solution

by:William
William earned 400 total points
ID: 19659453
In place of:
 string userState = "test message1";

Object userstate = MyEmail;

inside the callback:
In place of:
 String token = (string) e.UserState;

Email mail = e.UserState as Email; or Email mail = (Email)e.UserState;

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:newbieweb
ID: 19659475
and how to I use an HTML file as the body?
0
 

Author Comment

by:newbieweb
ID: 19659481
does the SMTP server need to be up and running for the email to go out?
0
 
LVL 11

Expert Comment

by:William
ID: 19659531
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
0
 
LVL 11

Expert Comment

by:William
ID: 19659565
For most of your email needs you can find awesome samples here:
http://www.systemwebmail.com/faq.aspx
0
 

Author Comment

by:newbieweb
ID: 19659570
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?
0
 
LVL 11

Expert Comment

by:William
ID: 19659609
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.
0
 

Author Comment

by:newbieweb
ID: 19659628
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.
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 19659931
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)
0
 

Author Comment

by:newbieweb
ID: 19674736
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.");
        }


0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 19674889
NetworkCredential nc = new NetworkCredential(Username, password); //required by your email server ...
client.UseDefaultCredentials = false;
client.Credentials = nc;
0
 

Author Comment

by:newbieweb
ID: 19678108
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
0
 
LVL 37

Accepted Solution

by:
gregoryyoung earned 1600 total points
ID: 19678284
umm yeah ...
            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.");
        }

after sending async you proceed to dispose the message ... dont dispose it then .. dispose it in your call back that the message has been completed.

Its being sent in another thread ... you dispose it before the other thread is done.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses
Course of the Month17 days, 11 hours left to enroll

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question