Sending Email. The simplest form of sending data to the mail using HTML and PHP Sending an email with an attachment c#

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

Let's start, perhaps

For sending e-mail we need to use three objects. System.Net.Mail.SmtpClient to send a message, System.Net.Mail.MailMessage to represent a message, and System.Net.NetworkCredential to authorize.

Let's create a client:

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

constructor 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). As well as the login and password for the smtp client. Then we will send an email 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 a 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; // message body in html? msg.IsBodyHtml = false; client.Credentials = new NetworkCredential("login", "password"); client.Send(msg);

That's all. Be sure to enter all 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 mr olympia October 14, 2013 at 07:29 pm

Programmatically send email using various services

  • .net,

Very often you have to deal with sending emails from program code. You don't have 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 non-working or outdated solution, or simply written illiterately.

The first thing you should not do with these examples is to use System.Web.Mail, which has been deprecated for a long time, and since visual studio 2010 the System.Web library can't even be added without knowing full path to the corresponding DLL.
Instead, it is proposed to use the System.Net library.
using System.Net; using System.Net.Mail;
So, the simplest, it is also the most important and often used is sending a letter from your mail server The on which the SMTP client is configured. As you understand, the server can be either the one on which the application is running, or a remote one, on which you have the rights to send letters without additional authorization.

Sample code for sending email from local machine:
", "[email protected]"))( mm.Subject = "Mail Subject"; mm.Body = "Mail Body"; mm.IsBodyHtml = false; using (SmtpClient sc = new SmtpClient("127.0. mail server and port if required sc.Send(mm); ) )

Using mail 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 you have Mailbox on the mail.ru service ends with inbox.ru, list.ru or bk.ru, then the address of the SMTP server (smtp.inbox.ru, smtp.list.ru and smtp.bk.ru) changes accordingly.

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 the authorization rules.

It must also be remembered that almost all third-party email services impose limits on the number of emails sent in a period of time.

Tags: email, sending emails, smtp

One of the most requested functions on the site is the application or order form, the data from which is sent to the mail of 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 will require the use of the HTML markup language and the language PHP programming.

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 bit more complicated.

It is not difficult for a programmer to create such a form, but some actions may seem difficult for an HTML coder.

Creating an html submit form

The first line will be next

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

Let's get back to the form. The second line will contain a field for entering a 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 enters 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 specified as email, and the explanation is specified for the user to enter their email address in this form.

The next line will be the submit button:

And the last line in the form will be the tag

Now let's put it all together.





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





Create a file that accepts data from an HTML form

This will be a file called send.php

In the file, at the first stage, you need to receive 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 to which the data from the form is passed. In the html form, the send method method="post" is specified. Thus, two variables are taken from html forms. For the purposes of protecting your site, you need to pass these variables through several filters - php functions.

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

In this case, new variables in php are not created, but existing ones are used. What the filter will do is convert 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 string, if any:

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

There are other functions that allow you to filter php variables. Their use depends on how much you are afraid that an attacker will try to add program code to this form of sending data to html mail.

Validate data passed from HTML form to PHP file

In order to check if this code works, if the 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 in order to separate the output of php variables into different lines.

Sending the received data from the HTML form to the mail using PHP

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

mail("to which address to send", "the 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 email should be clear, and the message of the email should contain what the user has specified in the HTML form.

mail(" [email protected]", "Application from the site", "Name:".$fio.". Email: ".$email ,"From: [email protected]\r\n");

You need to add a condition that will check if the form was sent using PHP to the specified email address.

if (mail(" [email protected]", "Order from the site", "Name:".$fio.". Email: ".$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", "Name:".$fio.". Email: ".$email ,"From: [email protected]\r\n"))
( echo "message sent successfully";
) else (
echo "errors occurred while sending the message";
}?>

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

Place HTML and PHP form submission code in one file

In the comments to this article, many people ask how to make both the HTML form and the PHP code for sending data to the mail be in one file, 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 passed from the form). That is, if the variables in the array do not exist, then you need to show the user a form. Otherwise, you need to take the data from the array and send it to the addressee.

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



Website application form


//check if variables exist in 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", "Name:".$fio.". Email: ".$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 PHP isset() 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 didn't put an exclamation mark, then 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, then do not forget to rename the file name and in the line

. The form must link to the same page, such as 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 a mistake in the page code. You need to turn on the display of all errors in PHP and then you will see where the error was made. Add to 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 won't work. It is desirable that this is not a local server, as it is not always configured to send data to an external mail server. If you run the code on a server other than the server, then you will see the PHP code right on the page.

Thus, for correct work, I recommend placing the send.php file on the hosting of the site. There, as a rule, everything is already configured.

Another common mistake is when the notification "Message sent successfully" 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", "Name:".$fio.". Email: ".$email ,"From: [email protected]\r\n"))

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

Last update: 31.10.2015

SMTP (Simple Mail Transfer Protocol) is used to send mail over the Internet. This protocol specifies how mail servers interact when sending email.

To work with the SMTP protocol and send e-mail in .NET, the SmtpClient class from the System.Net.Mail namespace is intended.

This class defines a number of properties that allow you to customize the send:

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

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

    Credentials: sender authentication data

    EnableSsl: Specifies whether the SSL protocol 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 email attachments

    Body: directly the text of the letter

    From: sender's address. Represents a MailAddress object

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

    Subject: defines the subject of the email

    IsBodyHtml: Indicates if the email represents content with html code

Let's use these classes and send the email:

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 the 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); // mail subject m.Subject = "Test"; // mail text m.Body = "

Letter-test of the smtp-client

"; // the letter represents the html code m.IsBodyHtml = true; // smtp server address and 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, in which the MailMessage object is passed.

We can also use the asynchronous version of sending with 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 = "Smtp client work test letter 2"; SmtpClient smtp = new SmtpClient("smtp.gmail.com" , 587); smtp.Credentials = new NetworkCredential(" [email protected]", "mypassword"); smtp.EnableSsl = true; await smtp.SendMailAsync(m); Console.WriteLine("Mail sent"); ) ) )

Add attachments

We can attach attachments to emails 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"));

Very often you have to deal with sending emails from program code. You don't have 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 non-working or outdated solution, or simply written illiterately.

The first thing you should not do with 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.
Instead, it is proposed to use the System.Net library.
using System.Net; using System.Net.Mail;
So, the simplest, it is also the most important and often used, is sending a letter from your mail server, on which the SMTP client is configured. As you understand, the server can be either the one on which the application is running, or a remote one, on which you have the rights to send letters without additional authorization.

Sample code for sending email from local machine:
", "[email protected]"))( mm.Subject = "Mail Subject"; mm.Body = "Mail Body"; mm.IsBodyHtml = false; using (SmtpClient sc = new SmtpClient("127.0. mail server and port if required sc.Send(mm); ) )

Using mail 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 with 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 the authorization rules.

It must also be remembered that almost all third-party email services impose limits on the number of emails sent in a period of time.

Tags: email, sending emails, smtp



Loading...
Top