How to send a message by email c. Working with email. Letter test of smtp client operation

Hello. Since my graphomania is progressing, I decided to add another article. The article, as always, will contain examples in C#, but a more or less skilled VB specialist will easily rewrite all the code under VB.NET.

Let's get started, I guess

To send E-Mail we need to use three objects. System.Net.Mail.SmtpClient to send the message, System.Net.Mail.MailMessage to present the message, and System.Net.NetworkCredential to authorize.

Let's create a client:

Var client = new SmtpClient("$Mail-Server-Address$", $Mail-Server-Port$);

Designer reference:

SmtpClient(string host, int port);

Let's create an instance of the MailMessage class:

Var msg = new MailMessage("from", "to");

Now let’s set the subject and content of the letter (by the way, everything can be set in the constructor). And also the login and password for the smtp client. Then we will send the letter using the Send method of our client object:

Var client = new SmtpClient("smtp.yandex.ru"); var msg = new MailMessage("from", "to"); msg.Subject = "My test message"; msg.Body = "Hello, my friend! Just imagine that I just wrote an incredible program to send this meaningless letter to you a billion times only by several clicks!"; msg.SubjectEncoding = Encoding.UTF8; msg.BodyEncoding = Encoding.UTF8; // priority msg.Priority = MailPriority.High; // email body in html? msg.IsBodyHtml = false; client.Credentials = new NetworkCredential("login", "password"); client.Send(msg);

That's all. Don't forget to fill in all the required information correctly.


Comments ()

ruslang02 30

CoolHacker, can I borrow this code from you for part 3 of the web browser?

Coolhacker 770 ruslang02 30

Thank you, I will use it to send links by e-mail
like in FireFox

LetSevI 10

Last updated: 10/31/2015

To send mail on the Internet, the SMTP (Simple Mail Transfer Protocol) protocol is used. This protocol specifies how mail servers communicate when transmitting email.

The SmtpClient class from the System.Net.Mail namespace is designed to work with the SMTP protocol and send email in .NET.

This class defines a number of properties that allow you to configure sending:

    Host: smtp server from which mail is sent. For example, smtp.yandex.ru

    Port: Port used by the smp server. If not specified, then port 25 is used by default.

    Credentials: sender's authentication data

    EnableSsl: Specifies whether SSL will be used when sending

Another key class that is used when sending is MailMessage. This class represents the message being sent. Among its properties are the following:

    Attachments: contains all attachments to the letter

    Body: the text of the letter itself

    From: sender's address. Represents a MailAddress object

    To: recipient's address. Also represents a MailAddress object

    Subject: defines the subject of the letter

    IsBodyHtml: Indicates whether the email represents content with html code

Let's use these classes and send a letter:

Using System; using System.Net; using System.IO; using System.Threading.Tasks; using System.Net.Mail; namespace NetConsoleApp ( class Program ( static void Main(string args) ( // sender - set the address and name displayed in the letter MailAddress from = new MailAddress(" [email protected]", "Tom"); // to whom we send MailAddress to = new MailAddress(" [email protected]"); // create a message object MailMessage m = new MailMessage(from, to); // subject of the letter m.Subject = "Test"; // text of the letter m.Body = "

Letter test of smtp client operation

"; // the letter represents the html code m.IsBodyHtml = true; // the address of the smtp server and the port from which we will send the letter SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); // login and password smtp.Credentials = new NetworkCredential(" [email protected]", "mypassword"); smtp.EnableSsl = true; smtp.Send(m); Console.Read(); ) ) )

To send, the Send() method is used, to which the MailMessage object is passed.

We can also use the asynchronous version of sending using the SendMailAsync method:

Using System; using System.Net; using System.IO; using System.Threading.Tasks; using System.Net.Mail; namespace NetConsoleApp ( class Program ( static void Main(string args) ( SendEmailAsync().GetAwaiter(); Console.Read(); ) private static async Task SendEmailAsync() ( MailAddress from = new MailAddress(" [email protected]", "Tom"); MailAddress to = new MailAddress(" [email protected]"); MailMessage m = new MailMessage(from, to); m.Subject = "Test"; m.Body = "Letter test 2 of the smtp client"; SmtpClient smtp = new SmtpClient("smtp.gmail.com" , 587); smtp.Credentials = new NetworkCredential(" [email protected]", "mypassword"); smtp.EnableSsl = true; await smtp.SendMailAsync(m); Console.WriteLine("Message sent"); ) ) )

Adding attachments

We can attach attachments to a letter using the Attachments property. Each attachment represents a System.Net.Mail.Attachment object:

MailAddress from = new MailAddress(" [email protected]", "Tom"); MailAddress to = new MailAddress(" [email protected]"); MailMessage m = new MailMessage(from, to); m.Attachments.Add(new Attachment("D://temlog.txt"));

One of the most popular functions on the site is the application or order form, the data from which is sent by email to the site owner. As a rule, such forms are simple and consist of two or three fields for data entry. How to create such an order form? This requires the use of HTML markup language and PHP programming language.

The HTML markup language itself is simple; you just need to figure out how and where to put certain tags. With the PHP programming language, things are a little more complicated.

For a programmer, creating such a form is not difficult, but for an HTML layout designer, some actions may seem difficult.

Create a data submission form in html

The first line will be as follows

This is a very important element of the form. In it we indicate how the data will be transferred and to which file. In this case, everything is transferred using the POST method to the send.php file. The program in this file must accordingly receive the data, it will be contained in the post array, and send it to the specified email address.

Let's get back to form. The second line will contain a field for entering your full name. Has the following code:

The form type is text, that is, the user will be able to enter or copy text here from the keyboard. The name parameter contains the name of the form. In this case, it is fio; it is under this name that everything that the user entered in this field will be transmitted. The placeholder parameter specifies what will be written in this field as an explanation.

Next line:

Here, almost everything is the same, but the name for the field is email, and the explanation is that the user enters his email address in this form.

The next line will be the "send" button:

And the last line in the form will be the tag

Now let's put everything together.





Now let's make the fields in the form mandatory. We have the following code:





Create a file that accepts data from the HTML form

This will be a file called send.php

In the file, at the first stage, you need to accept data from the post array. To do this, we create two variables:

$fio = $_POST["fio"];
$email = $_POST["email"];

Variable names in PHP are preceded by a $ sign, and a semicolon is placed at the end of each line. $_POST is an array into which data from the form is sent. In the html form, the sending method is specified as method="post". So, two variables from the html form are accepted. To protect your site, you need to pass these variables through several filters - php functions.

The first function will convert all the characters that the user will try to add to the form:

In this case, new variables are not created in php, but existing ones are used. What the filter will do is transform the character "<" в "<". Также он поступить с другими символами, встречающимися в html коде.

The second function decodes the url if the user tries to add it to the form.

$fio = urldecode($fio);
$email = urldecode($email);

With the third function we will remove spaces from the beginning and end of the line, if any:

$fio = trim($fio);
$email = trim($email);

There are other functions that allow you to filter php variables. Their use depends on how concerned you are that an attacker will try to add program code to this html email submission form.

Validation of data transferred from HTML form to PHP file

In order to check whether this code works and whether data is being transferred, you can simply display it on the screen using the echo function:

echo $fio;
echo "
";
echo $email;

The second line here is needed to separate the output of php variables into different lines.

Sending received data from an HTML form to email using PHP

To send data by email, you need to use the mail function in PHP.

mail("to which address to send", "subject of the letter", "Message (body of the letter)","From: from which email the letter is sent \r\n");

For example, you need to send data to the email of the site owner or manager [email protected].

The subject of the letter should be clear, and the message of the letter should contain what the user specified in the HTML form.

mail(" [email protected]", "Application from the site", "Full name:".$fio.". E-mail: ".$email ,"From: [email protected]\r\n");

It is necessary to add a condition that will check whether the form was sent using PHP to the specified email address.

if (mail(" [email protected]", "Order from the site", "Full name:".$fio.". E-mail: ".$email ,"From: [email protected]\r\n"))
{
echo "message sent successfully";
) else (
}

Thus, the program code of the send.php file, which will send the HTML form data to the mail, will look like this:

$fio = $_POST["fio"];
$email = $_POST["email"];
$fio = htmlspecialchars($fio);
$email = htmlspecialchars($email);
$fio = urldecode($fio);
$email = urldecode($email);
$fio = trim($fio);
$email = trim($email);
//echo $fio;
//echo "
";
//echo $email;
if (mail(" [email protected]", "Application from the site", "Full name:".$fio.". E-mail: ".$email ,"From: [email protected]\r\n"))
( echo "message sent successfully";
) else (
echo "errors occurred while sending the message";
}?>

Three lines to check if the data is being transferred to the file are commented out. If necessary, they can be removed, since they were needed only for debugging.

We place the HTML and PHP code for submitting the form in one file

In the comments to this article, many people ask the question of how to make sure that both the HTML form and the PHP code for sending data to email are in one file, and not two.

To implement this work, you need to place the HTML code of the form in the send.php file and add a condition that will check for the presence of variables in the POST array (this array is sent from the form). That is, if the variables in the array do not exist, then you need to show the user the form. Otherwise, you need to receive data from the array and send it to the recipient.

Let's see how to change the PHP code in the send.php file:



Application form from the site


//check if variables exist in the POST array
if(!isset($_POST["fio"]) and !isset($_POST["email"]))(
?>





) else (
//show the form
$fio = $_POST["fio"];
$email = $_POST["email"];
$fio = htmlspecialchars($fio);
$email = htmlspecialchars($email);
$fio = urldecode($fio);
$email = urldecode($email);
$fio = trim($fio);
$email = trim($email);
if (mail(" [email protected]", "Application from the site", "Full name:".$fio.". E-mail: ".$email ,"From: [email protected]\r\n"))(
echo "Message sent successfully";
) else (
echo "Errors occurred while sending the message";
}
}
?>

We check the existence of a variable in the POST array with the isset() PHP function. An exclamation point before this function in a condition means negation. That is, if the variable does not exist, then we need to show our form. If I hadn’t put the exclamation point, the condition would literally mean “if exists, then show the form.” And this is wrong in our case. Naturally, you can rename it to index.php. If you rename the file, do not forget to rename the file name in the line

. The form should link to the same page, for example index.php. I added the page title to the code.

Common errors that occur when submitting a PHP form from a website

The first, probably the most popular mistake, is when you see a blank white page with no messages. This means that you made an error in the page code. You need to enable display of all errors in PHP and then you will see where the error was made. Add to the code:

ini_set("display_errors","On");
error_reporting("E_ALL");

The send.php file must only be run on the server, otherwise the code simply will not work. It is advisable that this is not a local server, since it is not always configured to send data to an external mail server. If you run the code not on the server, then the PHP code will be displayed directly on the page.

Thus, for correct operation, I recommend placing the send.php file on the site hosting. As a rule, everything is already configured there.

Another common mistake is when the “Message sent successfully” notification appears, but the letter does not arrive in the mail. In this case, you need to carefully check the line:

if (mail(" [email protected]", "Order from the site", "Full name:".$fio.". E-mail: ".$email ,"From: [email protected]\r\n"))

Instead of [email protected] there must be an email address to which the letter should be sent, but instead[email protected] must be an existing email for this site. For example, for a website this will be . Only in this case a letter with the data from the form will be sent.

Very often you have to deal with sending emails from program code. You don't need to look far for examples.

This article is a hint and does not reveal anything new, but before writing it, I looked similar on the Internet and was quite surprised that almost everywhere they offer either a solution that is not working or outdated, or is simply written illiterately.

The first thing you shouldn’t do based on these examples is to use System.Web.Mail, which has long been outdated, and starting with Visual Studio 2010, you can’t even add the System.Web library without knowing the full path to the corresponding DLL.
It is proposed to use the System.Net library instead.
using System.Net; using System.Net.Mail;
So, the simplest thing, which is also the most important and frequently used, is sending a letter from your mail server on which an SMTP client is configured. As you understand, the server can be either the one on which the application runs, or a remote one on which you have the rights to send letters without additional authorization.

Sample code for sending a letter from a local machine:
", "[email protected]"))( mm.Subject = "Mail Subject"; mm.Body = "Mail Body"; mm.IsBodyHtml = false; using (SmtpClient sc = new SmtpClient("127.0.0.1"))(//The address should be here mail server and port, if required sc.Send(mm);

Using email services such as Gmail, Yandex, Mail.ru, etc. everything is the same, only parameters with authorization are added.

SMTP server: smtp.gmail.com
Port: 587
using (MailMessage mm = new MailMessage("Name ", "[email protected]"))( mm.Subject = "Mail Subject"; mm.Body = "Mail Body"; mm.IsBodyHtml = false; using (SmtpClient sc = new SmtpClient("smtp.gmail.com", 587))( sc. EnableSsl = true; sc.DeliveryMethod = SmtpDeliveryMethod.Network; sc.UseDefaultCredentials = false; sc.Credentials = new NetworkCredential(" [email protected]", "GmailPassword"); sc.Send(mm); ) )

SMTP server: smtp.yandex.ru
Port: 25
using (MailMessage mm = new MailMessage("Name ", "[email protected]"))( mm.Subject = "Mail Subject"; mm.Body = "Mail Body"; mm.IsBodyHtml = false; using (SmtpClient sc = new SmtpClient("smtp.yandex.ru", 25))( sc. EnableSsl = true; sc.DeliveryMethod = SmtpDeliveryMethod.Network; sc.UseDefaultCredentials = false; sc.Credentials = new NetworkCredential(" [email protected]", "YandexPassword"); sc.Send(mm); ) )

SMTP server: smtp.mail.ru
Port: 25
using (MailMessage mm = new MailMessage("Name ", "[email protected]"))( mm.Subject = "Mail Subject"; mm.Body = "Mail Body"; mm.IsBodyHtml = false; using (SmtpClient sc = new SmtpClient("smtp.mail.ru", 25))( sc. EnableSsl = true; sc.DeliveryMethod = SmtpDeliveryMethod.Network; sc.UseDefaultCredentials = false; sc.Credentials = new NetworkCredential(" [email protected]", "MailRuPassword"); sc.Send(mm); ) )
If your mailbox on the mail.ru service ends in inbox.ru, list.ru or bk.ru, then the SMTP server address changes accordingly (smtp.inbox.ru, smtp.list.ru and smtp.bk.ru ).

As you can see, in order to use any other mail service in your programs, you only need to find out the SMTP server address and port, as well as authorization rules.

It is also important to remember that almost all third-party email services impose limits on the number of emails sent in a period of time.

Tags: email, sending letters, smtp