C and C # can be used to send simple emails,

Source: Internet
Author: User
Tags email account mailmessage smtpclient

C and C # can be used to send simple emails,

The content is sent in two ways -- 1. send an email in C Language 2.C# send an email

1. Send emails in C Language

Simple Analysis of the steps for sending emails in C language:

1. Create a TCP connection socket ()

2. connect to the mailbox server SOCKADDR_IN, connect ()

3. log on to the "EHLO smtp.163.com \ r \ n" → "auth login \ r \ n" through email user and Password Authentication"

4. Send the subject content of the email

A. Send "mail from: <" MAIL sender address "> \ r \ n "//

B. Send "RCPT TO: <" email recipient's address "> \ r \ n"

C. Send "DATA \ r \ n"

D. Send the mail header (From, To, Subject, Date, etc.) and the mail body (the mail body can be blank)

E. Add attachments (you can add multiple attachments or not)

5. log out and send "QUIT \ r \ n"

6. disable TCP connection closesocket (connection );

The key code of C language is as follows:

// Create a TCP connection

1 if ((connection = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)2 {3     return INVALID_SOCKET;4 }

// Connect to the mailbox Server

1 void ConnectToServer (SOCKET connection, const char * serverName) 2 {3 // set the SockAddr_In address structure 4 SOCKADDR_IN serAddr; 5 serAddr. sin_family = AF_INET; 6 serAddr. sin_port = htons (SMTP_PORT); 7 // from CAsysSocket: Connect () 8 serAddr. sin_addr.s_addr = inet_addr (serverName); 9 if (serAddr. sin_addr.s_addr = INADDR_NONE) 10 {11 LPHOSTENT lphost; 12 lphost = gethostbyname (serverName); 13 if (lphost! = NULL) 14 serAddr. sin_addr.s_addr = (LPIN_ADDR) lphost-> h_addr)-> S_un.S_addr; 15 else16 return; 17} 18 // connect to server 19 connect (connection, (SOCKADDR *) & serAddr, sizeof (serAddr) = SOCKET_ERROR) 20 return; 21}

// Authenticate Logon

1 // authenticated login 2 BOOL AuthLogin (SOCKET connection, const char * serverName, const char * userAccount, const char * password) 3 {4 // send EHLO % SMTP-Server Name % Note: HELO does not carry authentication, while EHLO does carry authentication 5 char szHello [PARA_BUF] = {0 }; 6 sprintf (szHello, "EHLO % s \ r \ n", serverName); // "EHLO % s \ r \ n" 7 if (! Send_rev (connection, szHello, GENERIC_SUCCESS) 8 return FALSE; 9 10 // send AUTH LOGIN11 if (! Send_rev (connection, "auth login \ r \ n", AUTHLOGIN_SUCCESS) // "auth login \ r \ n" 12 return FALSE; 13 14 // send Base64 encoded user account 15 char szAccount [100] = {0}; 16 base64_encode (userAccount, strlen (userAccount), & szAccount ); // base64 encoding 17 strcat (szAccount, "\ r \ n"); 18 if (! Send_rev (connection, szAccount, AUTHLOGIN_SUCCESS) // account 19 return FALSE; 20 21 // send the Base64 encoded password 22 char szPassword [100] = {0 }; 23 base64_encode (password, strlen (password), & szPassword); 24 strcat (szPassword, "\ r \ n"); 25 if (! Send_rev (connection, szPassword, AUTH_SUCCESS) // password 26 return FALSE; 27 return TRUE; 28}

// Send an email (including the user's exit Operation QUIT)

1 // send mail 2 BOOL SendMail (SOCKET connection, const char * from, const char * to, 3 const char * subject, const char * body, 4 const char * userName, const char * filePath) 5 {6 char szFrom [PARA_BUF] = {0}; 7 char szTo [PARA_BUF] = {0}; 8 char szSubject [PARA_BUF] = {0 }; 9 char szBodyHead [PARA_BUF * 10] = {0}; 10 char szBody [PARA_BUF * 20] = {0}; 11 12 char szDateTime [PARA_BUF] = {0 }; 13 char * szCont Ent = NULL; 14 // the content of the email, including the body text and attachment content. 15 if (! Chars_malloc (& szContent, MAX_FILE_SIZE * 4/3 + M) 16 {17 return FALSE; 18} 19 20 // send Mail From21 sprintf (szFrom, "mail from: <% s> \ r \ n ", from); // mail from: <% s> \ r \ n22 if (! Send_rev (connection, szFrom, GENERIC_SUCCESS) 23 return FALSE; 24 25 // The RCPT TO26 sprintf (szTo, "rcpt to: <% s> \ r \ n ", to); // rcpt to: <% s> \ r \ n27 if (! Send_rev (connection, szTo, GENERIC_SUCCESS) 28 return FALSE; 29 30 // send DATA \ r \ n31 if (! Send_rev (connection, "DATA \ r \ n", DATA_SUCCESS) // DATA \ r \ n32 return FALSE; 33 34 // perform Body processing 35 sprintf (szFrom, "FROM: % s <% s> \ r \ n ", userName, from); // content36 sprintf (szTo," TO: <% s> \ r \ n ", ); 37 time_t ltime = time (NULL); 38 _ tzset (); 39 sprintf (szDateTime, "Date: % s", ctime (& ltime); 40 sprintf (szSubject, "Subject: % s \ r \ n", subject); 41 42 sprintf (szBodyHead, "X_Mailer: ntSmtp [ch] \ r \ n", subject); 43 str Cat (szBodyHead, "MIME_Version: 1.0 \ r \ n"); 44 strcat (szBodyHead, "Content-type: multipart/mixed; boundary = ntSmtp \ r \ n "); 45 strcat (szBodyHead," -- ntSmtp \ r \ n "); 46 strcat (szBodyHead," Content-type: text/plain; Charset = gb2312 \ r \ n "); 47 strcat (szbodyheader," Content_Transfer-Encoding: 8bit \ r \ n "); 48 49 sprintf (szBody, "% s \ r \ n", body); 50 51 // content of each part connected to the content 52 strcat (szContent, szFrom); 53 strcat (szCont Ent, szTo); 54 strcat (szContent, szDateTime); 55 strcat (szContent, szSubject); 56 strcat (szContent, szBodyHead); 57 strcat (szContent, szBody ); 58 59 if (filePath! = NULL) 60 {// Add the attachment content to szContent61 AppendAttachment (& szContent, filePath); 62 // AppendAttachment (& szContent, filePath ); 63} 64 // Add end mark 65 strcat (szContent, "\ r \ n. \ r \ n "); // \ r \ n. \ r \ n66 67 // send Content68 if (! Send_rev (connection, szContent, GENERIC_SUCCESS) 69 return FALSE; 70 71 // send Quit, log out 72 if (! Send_rev (connection, "QUIT \ r \ n", QUIT_SUCCESS) // "QUIT \ r \ n" 73 return FALSE; 74 75 free (szContent); 76 return TRUE; 77}


 

II. C # send emails

To send emails through C #, you do not need the C language to grasp many details in the connection communication process,

For simple mail sending, you only need to use two classes. One is the MailMessage class, which defines

A complete email contains many required information (including the sender, recipient, subject, body content, attachments, and other information ),

The other is the SmtpClient class, which is used for server-side operations. Through the objects of this class, you can set

The address of the mailbox server (for example, smtp.163.com), the login account and password of the mailbox, etc.

You can send the message to the specified mailbox.

C # simple analysis of mail sending steps:

1. Create a MailMessage object and set the member data of the MailMessage, including From, To, Subject, Body, Attachments, and other information.

2. Create the Server Object SmtpClient, set the server, email account, and password.

3. Send the MailMessage through the SmtpClient object. Normal and asynchronous sending can be performed (without blocking the thread ).

 

C # the key code is as follows:

// Send mail Asynchronously

1 // send button 2 private void btn_Send_Click (object sender, EventArgs e) 3 {4 // create MailMessage object 5 MailAddress from = new MailAddress ("ntsmtp@163.com "); 6 MailAddress to = new MailAddress ("miaosha5s@sohu.com"); 7 MailMessage mailMessage = new MailMessage (from, to); 8 mailMessage. subject = "topic"; 9 mailMessage. body = "this is an email from afar. "; 10 11 Attachment attachment01 = new Attachment (" E: \ 01.jpg"); // Appendix 12 Attachme Nt attachment02 = new Attachment ("E: \ 02.mp3"); 13 mailMessage. attachments. add (attachment01); 14 mailMessage. attachments. add (attachment02); 15 16 // create SmtpClient object email server smtp.163.com17 SmtpClient smtpClient = new SmtpClient ("smtp.163.com"); 18 smtpClient. usedefacrecredentials = true; 19 smtpClient. credentials = 20 new NetworkCredential ("email account", "Logon password"); // email authenticated logon 21 // smtpClient. timeout = 5000; 22 try23 {24 // Use asynchronous transmission without blocking the thread 25 smtpClient. sendCompleted + = new // call callback function 26 SendCompletedEventHandler (SendCompletedCallback); 27 smtpClient. sendAsync (mailMessage, mailMessage); 28} 29 catch (Exception ex) 30 {31 mailMessage. dispose (); // actively releases the resource 32 smtpClient. dispose (); 33 MessageBox. show ("failed to send! "+ System. Environment. NewLine + 34" error Message: "+ ex. Message); 35} 36 return; 37}

// Callback function after asynchronous sending is completed:

1 // callback function for asynchronous mail completion 2 public static void SendCompletedCallback (object sender, 3 AsyncCompletedEventArgs e) 4 {5 SmtpClient smtpClient = (SmtpClient) sender; 6 // MailMessage mailMessage = (MailMessage) e. userState; 7 if (e. cancelled) 8 {9 MessageBox. show ("Send canceled. "); 10} 11 if (e. error! = Null) 12 {13 MessageBox. show ("error message:" + e. error. toString (); 14} 15 else16 {17 MessageBox. show ("Message Sent. "); 18 smtpClient. dispose (); 19 // mailMessage. dispose (); 20} 21}

 

 

Conclusion: The mail sending function is implemented in two ways, and the differences between the two languages can be compared,

The implementation of C language focuses more on procedures and details. You need to have a deep understanding of network and SMTP protocols,

The advantage is that the mail sending process can be operated more directly. The disadvantage is that the implementation is cumbersome and exception-prone.

The implementation of C # is more concise and clear. It encapsulates many details in the mail sending process. These details are not

Necessary, the user only needs to know the use of several important classes (MailMessage, SmtpClient class), and the program generally compares

The C program is stable, and it is not prone to exception errors.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.