Меню Закрыть

Asp newsid e mail

Содержание

Отправка email в ASP.NET Core

На данный момент .NET Core по умолчанию не предоставляет готового функционала для работы с протоколом SMTP, поэтому нам надо использовать сторонние решения, например, MailKit, SendGrid. Либо использовать зависимости полноценного .NET Framework в виде функциональности пространства имен System.Net.Smtp, но в этом случае мы уйдем от кроссплатформенности в строну одноплатформенного решения.

В данном случае мы будем использовать MailKit как наиболее простое и в то же время довольно насыщенное в плане функциональности решение. Для его установки добавим в проект через NuGet соответствующий пакет:

После сохранения файла project.json и добавления всех необходимых пакетов добавим в проект новый класс. Назовем его EmailService и определим в нем следующий код:

В классе определен асинхронный метод SendEmailAsync() , который в качестве параметров принимает email получателя сообщения, тему письма и его текст.

Для создания объекта отправляемого сообщения используется класс MimeMessage . Для определения отправителя в его коллекцию From добавляется объект MailboxAddress. Теоретически может быть указано несколько отправителей.

Все получатели письма добавляются в коллекцию To также в виде объекта MailboxAddress.

Тело сообщения, которое представлено свойством Body, может представлять как простой текст, так и какое-то другое содержимое. Например, в данном случае указано, что сообщение будет иметь формат html.

Для простого текста мы могли бы указать:

Либо использовать значение MimeKit.Text.TextFormat.Plain .

Непосредственно отправление производится с помощью класса SmtpClient . Причем весь процесс разбивается на ряд этапов:

Подключение к серверу

Аутентификация (при ее необходимости)

Собственно отправка сообщения

При подключении в метод ConnectAsync() передаются smtp-адрес сервера, номер порта, и логическое значение, указывающее, будет ли применяться SSL. В данном случае SSL не применяется, поэтому стоит значение false .

Для аутентификации в метод AuthenticateAsync() передаются наши логин и пароль на сервере.

Хотя здесь все методы асинхронные, но это необязательно. Мы можем использовать и синхронный API:

После определения класса мы можем его использовать, например, в контроллере:

This article explains how to send an email message from a website when you use ASP.NET Web Pages (Razor).

What you’ll learn:

  • How to send an email message from your website.
  • How to attach a file to an email message.

This is the ASP.NET feature introduced in the article:

Software versions used in the tutorial

  • ASP.NET Web Pages (Razor) 3

This tutorial also works with ASP.NET Web Pages 2.

Sending Email Messages from Your Website

There are all sorts of reasons why you might need to send email from your website. You might send confirmation messages to users, or you might send notifications to yourself (for example, that a new user has registered.) The WebMail helper makes it easy for you to send email.

To use the WebMail helper, you have to have access to an SMTP server. (SMTP stands for Simple Mail Transfer Protocol.) An SMTP server is an email server that only forwards messages to the recipient’s server — it’s the outbound side of email. If you use a hosting provider for your website, they probably set you up with email and they can tell you what your SMTP server name is. If you’re working inside a corporate network, an administrator or your IT department can usually give you the information about an SMTP server that you can use. If you’re working at home, you might even be able to test using your ordinary email provider, who can tell you the name of their SMTP server. You typically need:

  • The name of the SMTP server.
  • The port number. This is almost always 25. However, your ISP may require you to use port 587. If you are using secure sockets layer (SSL) for email, you might need a different port. Check with your email provider.
  • Credentials (user name, password).

In this procedure, you create two pages. The first page has a form that lets users enter a description, as if they were filling in a technical-support form. The first page submits its information to a second page. In the second page, code extracts the user’s information and sends an email message. It also displays a message confirming that the problem report has been received.

To keep this example simple, the code initializes the WebMail helper right in the page where you use it. However, for real websites, it’s a better idea to put initialization code like this in a global file, so that you initialize the WebMail helper for all files in your website. For more information, see Customizing Site-Wide Behavior for ASP.NET Web Pages.

Create a new website.

Add a new page named EmailRequest.cshtml and add the following markup:

Notice that the action attribute of the form element has been set to ProcessRequest.cshtml. This means that the form will be submitted to that page instead of back to the current page.

Add a new page named ProcessRequest.cshtml to the website and add the following code and markup:

In the code, you get the values of the form fields that were submitted to the page. You then call the WebMail helper’s Send method to create and send the email message. In this case, the values to use are made up of text that you concatenate with the values that were submitted from the form.

The code for this page is inside a try/catch block. If for any reason the attempt to send an email doesn’t work (for example, the settings aren’t right), the code in the catch block runs and sets the errorMessage variable to the error that has occurred. (For more information about try/catch blocks or the

In the body of the page, if the errorMessage variable is empty (the default), the user sees a message that the email message has been sent. If the errorMessage variable is set to true, the user sees a message that there’s been a problem sending the message.

Notice that in the portion of the page that displays an error message, there’s an additional test: if(debuggingFlag) . This is a variable that you can set to true if you’re having trouble sending email. When debuggingFlag is true, and if there’s a problem sending email, an additional error message is displayed that shows whatever ASP.NET has reported when it tried to send the email message. Fair warning, though: the error messages that ASP.NET reports when it can’t send an email message can be generic. For example, if ASP.NET can’t contact the SMTP server (for example, because you made an error in the server name), the error is Failure sending mail .

Important When you get an error message from an exception object ( ex in the code), do not routinely pass that message through to users. Exception objects often include information that users should not see and that can even be a security vulnerability. That’s why this code includes the variable debuggingFlag that’s used as a switch to display the error message, and why the variable by default is set to false. You should set that variable to true (and therefore display the error message) only if you’re having a problem with sending email and you need to debug. Once you have fixed any problems, set debuggingFlag back to false.

Читайте также:  Как отличить оригинальный айфон от копии

Modify the following email related settings in the code:

Set your-SMTP-host to the name of the SMTP server that you have access to.

Set your-user-name-here to the user name for your SMTP server account.

Set your-account-password to the password for your SMTP server account.

Set your-email-address-here to your own email address. This is the email address that the message is sent from. (Some email providers don’t let you specify a different From address and will use your user name as the From address.)

Configuring Email Settings

It can be a challenge sometimes to make sure you have the right settings for the SMTP server, port number, and so on. Here are a few tips:

  • The SMTP server name is often something like smtp.provider.com or smtp.provider.net . However, if you publish your site to a hosting provider, the SMTP server name at that point might be localhost . This is because after you’ve published and your site is running on the provider’s server, the email server might be local from the perspective of your application. This change in server names might mean you have to change the SMTP server name as part of your publishing process.
  • The port number is usually 25. However, some providers require you to use port 587 or some other port.
  • Make sure that you use the right credentials. If you’ve published your site to a hosting provider, use the credentials that the provider has specifically indicated are for email. These might be different from the credentials you use to publish.
  • Sometimes you don’t need credentials at all. If you’re sending email using your personal ISP, your email provider might already know your credentials. After you publish, you might need to use different credentials than when you test on your local computer.
  • If your email provider uses encryption, you have to set WebMail.EnableSsl to true .

Run the EmailRequest.cshtml page in a browser. (Make sure the page is selected in the Files workspace before you run it.)

Enter your name and a problem description, and then click the Submit button. You’re redirected to the ProcessRequest.cshtml page, which confirms your message and which sends you an email message.

Sending a File Using Email

You can also send files that are attached to email messages. In this procedure, you create a text file and two HTML pages. You’ll use the text file as an email attachment.

In the website, add a new text file and name it MyFile.txt.

Copy the following text and paste it in the file:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Create a page named SendFile.cshtml and add the following markup:

Create a page named ProcessFile.cshtml and add the following markup:

Modify the following email related settings in the code from the example:

  • Set your-SMTP-host to the name of an SMTP server that you have access to.
  • Set your-user-name-here to the user name for your SMTP server account.
  • Set your-email-address-here to your own email address. This is the email address that the message is sent from.
  • Set your-account-password to the password for your SMTP server account.
  • Set target-email-address-here to your own email address. (As before, you’d normally send an email to someone else, but for testing, you can send it to yourself.)

В этой статье объясняется, как отправлять сообщения электронной почты из веб-сайта, при использовании веб-страниц ASP.NET (Razor). This article explains how to send an email message from a website when you use ASP.NET Web Pages (Razor).

Вы узнаете, как: What you’ll learn:

  • Как отправлять сообщения электронной почты с веб-сайта. How to send an email message from your website.
  • Как добавить файл в сообщение электронной почты. How to attach a file to an email message.

Это функция ASP.NET, впервые представленная в этой статье: This is the ASP.NET feature introduced in the article:

  • WebMail Вспомогательный. The WebMail helper.

Версии программного обеспечения, используемые в этом руководстве Software versions used in the tutorial

  • Веб-страниц ASP.NET (Razor) 3 ASP.NET Web Pages (Razor) 3

Этот учебник также работает с ASP.NET Web Pages 2. This tutorial also works with ASP.NET Web Pages 2.

Отправка сообщений электронной почты с веб-сайта Sending Email Messages from Your Website

Существует множество причин, почему может потребоваться отправка электронной почты с веб-сайта. There are all sorts of reasons why you might need to send email from your website. Может отправить подтверждение для пользователей, или может отправлять уведомления для себя (например, что новый пользователь зарегистрировал.) WebMail Вспомогательный упрощает для отправки электронной почты. You might send confirmation messages to users, or you might send notifications to yourself (for example, that a new user has registered.) The WebMail helper makes it easy for you to send email.

Чтобы использовать WebMail вспомогательного приложения, у вас есть доступ к SMTP-сервер. To use the WebMail helper, you have to have access to an SMTP server. (Расшифровывается SMTP протокол SMTP.) SMTP-сервер — это почтовый сервер, который только перенаправляет сообщения на сервер получателя — сторона исходящие сообщения электронной почты. (SMTP stands for Simple Mail Transfer Protocol.) An SMTP server is an email server that only forwards messages to the recipient’s server — it’s the outbound side of email. При использовании поставщика услуг размещения для веб-сайта, они, скорее всего, настраивается по электронной почте, и они расскажем вам, что такое имя сервера SMTP. If you use a hosting provider for your website, they probably set you up with email and they can tell you what your SMTP server name is. Если вы работаете в корпоративной сети, администратор или ваш ИТ-отдел обычно обеспечивает сведения о SMTP-сервер, который можно использовать. If you’re working inside a corporate network, an administrator or your IT department can usually give you the information about an SMTP server that you can use. Если вы работаете дома, вы даже можно протестировать с помощью поставщика обычные электронной почты, который можно сообщить имя SMTP-сервера. If you’re working at home, you might even be able to test using your ordinary email provider, who can tell you the name of their SMTP server. Обычно нужно: You typically need:

  • Имя SMTP-сервера. The name of the SMTP server.
  • Номер порта. The port number. Это почти всегда 25. This is almost always 25. Тем не менее поставщик услуг Интернета может потребоваться использовать порт 587. However, your ISP may require you to use port 587. Если вы используете протокол SSL (SSL) для электронной почты, может потребоваться другой порт. If you are using secure sockets layer (SSL) for email, you might need a different port. Обратитесь к поставщику услуг электронной почты. Check with your email provider.
  • Учетные данные (имя пользователя, пароль). Credentials (user name, password).
Читайте также:  Что лучше соковыжималка или соковарка отзывы

В этой процедуре вы создадите две страницы. In this procedure, you create two pages. Первая страница содержит форму, которая позволяет пользователям вводить описание, как если бы они заполнив форму технической поддержки. The first page has a form that lets users enter a description, as if they were filling in a technical-support form. Первая страница отправляет данные на вторую страницу. The first page submits its information to a second page. На второй странице код извлекает сведения о пользователе и отправляет сообщение электронной почты. In the second page, code extracts the user’s information and sends an email message. Она также отображает сообщение с подтверждением, что получен отчет о проблеме. It also displays a message confirming that the problem report has been received.

Для простоты в этом примере, этот код инициализирует WebMail вспомогательный справа на странице, где его использовать. To keep this example simple, the code initializes the WebMail helper right in the page where you use it. Тем не менее для реальных веб-сайтов, лучше поместить следующий код инициализации в глобальный файл, таким образом, необходимо инициализировать WebMail вспомогательный класс для всех файлов в веб-сайта. However, for real websites, it’s a better idea to put initialization code like this in a global file, so that you initialize the WebMail helper for all files in your website. Дополнительные сведения см. в разделе поведение Настройка сайта для веб-страниц ASP.NET. For more information, see Customizing Site-Wide Behavior for ASP.NET Web Pages.

Создание нового веб-сайта. Create a new website.

Добавьте новую страницу с именем EmailRequest.cshtml и добавьте следующую разметку: Add a new page named EmailRequest.cshtml and add the following markup:

Обратите внимание, что action атрибут элемента формы было присвоено ProcessRequest.cshtml. Notice that the action attribute of the form element has been set to ProcessRequest.cshtml. Это означает, что форма будет отправлена на эту страницу, вместо возврата в текущей страницы. This means that the form will be submitted to that page instead of back to the current page.

Добавьте новую страницу с именем ProcessRequest.cshtml на веб-сайт и добавьте следующий код и разметки: Add a new page named ProcessRequest.cshtml to the website and add the following code and markup:

В коде получить значения поля формы, которые были переданы на страницу. In the code, you get the values of the form fields that were submitted to the page. Затем можно вызвать WebMail вспомогательного приложения Send метод для создания и отправки сообщения электронной почты. You then call the WebMail helper’s Send method to create and send the email message. В этом случае значения, используемые состоят из текст, который вы можете сцеплять со значениями, которые были переданы из формы. In this case, the values to use are made up of text that you concatenate with the values that were submitted from the form.

Код для этой страницы находится внутри try/catch блока. The code for this page is inside a try/catch block. Если для какой-либо причине попытка отправить сообщение электронной почты не работает (например, параметры не требуются справа), код в catch блок выполняется и задает errorMessage переменной о возникшей ошибке. If for any reason the attempt to send an email doesn’t work (for example, the settings aren’t right), the code in the catch block runs and sets the errorMessage variable to the error that has occurred. (Дополнительные сведения о try/catch блоки или

В основной области страницы Если errorMessage переменная пуста (по умолчанию), пользователь видит сообщение, которое было отправлено сообщение электронной почты. In the body of the page, if the errorMessage variable is empty (the default), the user sees a message that the email message has been sent. Если errorMessage переменной присвоено значение true, который пользователь видит сообщение, что возникла ошибка при отправке сообщения. If the errorMessage variable is set to true, the user sees a message that there’s been a problem sending the message.

Обратите внимание, что в области страницы, которая отображает сообщение об ошибке, дополнительной проверки: if(debuggingFlag) . Notice that in the portion of the page that displays an error message, there’s an additional test: if(debuggingFlag) . Это переменная, которое можно задать значение true, если возникают проблемы при отправке сообщения электронной почты. This is a variable that you can set to true if you’re having trouble sending email. Когда debuggingFlag имеет значение true, и есть ли ошибка при отправке электронной почты, отображается сообщение об ошибке дополнительные, показывающее, все, что при попытке отправить сообщение электронной почты сообщает ASP.NET. When debuggingFlag is true, and if there’s a problem sending email, an additional error message is displayed that shows whatever ASP.NET has reported when it tried to send the email message. Равномерное предупреждение, однако: сообщения об ошибках, которые ASP.NET выдает сообщение, если оно не может отправлять сообщения электронной почты могут быть универсальными. Fair warning, though: the error messages that ASP.NET reports when it can’t send an email message can be generic. Например если ASP.NET не удается связаться с SMTP-сервера (например, из-за ошибки в имени сервера), ошибка Failure sending mail . For example, if ASP.NET can’t contact the SMTP server (for example, because you made an error in the server name), the error is Failure sending mail .

Важные при получении сообщения об ошибке из объекта исключения ( ex в коде), выполните не регулярно передать это сообщение по пользователям. Important When you get an error message from an exception object ( ex in the code), do not routinely pass that message through to users. Объекты исключения часто содержат сведения, пользователи не должны видеть и, даже к уязвимости системы безопасности. Exception objects often include information that users should not see and that can even be a security vulnerability. Вот почему этот код содержит переменную debuggingFlag , используемый как переключатель отображение сообщений об ошибках, почему переменной по умолчанию имеет значение false. That’s why this code includes the variable debuggingFlag that’s used as a switch to display the error message, and why the variable by default is set to false. Следует задавать эту переменную, равным true (и следовательно, будут отображаться сообщение об ошибке) только при возникновении проблемы с отправкой электронной почты и необходимо выполнить отладку. You should set that variable to true (and therefore display the error message) only if you’re having a problem with sending email and you need to debug. После устранения проблемы задайте debuggingFlag обратно в значение false. Once you have fixed any problems, set debuggingFlag back to false.

Читайте также:  Dual ddr 400 материнская плата

Изменить связанные параметры в коде, электронной почты следующее: Modify the following email related settings in the code:

Задайте your-SMTP-host имя SMTP-сервера, у вас есть доступ к. Set your-SMTP-host to the name of the SMTP server that you have access to.

Задайте your-user-name-here имени пользователя для учетной записи сервера SMTP. Set your-user-name-here to the user name for your SMTP server account.

Задайте your-account-password на пароль для учетной записи сервера SMTP. Set your-account-password to the password for your SMTP server account.

Задайте your-email-address-here на адрес электронной почты. Set your-email-address-here to your own email address. Это адрес электронной почты, которые отправляются сообщения. This is the email address that the message is sent from. (Некоторые поставщики электронной почты не позволяют задать другой From адресов и будет использовать имя пользователя как From адрес.) (Some email providers don’t let you specify a different From address and will use your user name as the From address.)

Настройка параметров электронной почты Configuring Email Settings

Он может быть сложной задачей, иногда для того, чтобы убедиться в том, что у вас есть нужные параметры для SMTP-сервера, номер порта и т. д. It can be a challenge sometimes to make sure you have the right settings for the SMTP server, port number, and so on. Несколько советов: Here are a few tips:

  • Имя SMTP-сервера часто выглядит примерно так smtp.provider.com или smtp.provider.net . The SMTP server name is often something like smtp.provider.com or smtp.provider.net . Однако если вы публикуете веб-узла поставщика услуг размещения, имя SMTP-сервера на этом этапе может быть localhost . However, if you publish your site to a hosting provider, the SMTP server name at that point might be localhost . Это обусловлено тем, после того как вы опубликовали и ваш сайт работает на сервере поставщика, сервера электронной почты может быть локальным с точки зрения приложения. This is because after you’ve published and your site is running on the provider’s server, the email server might be local from the perspective of your application. Это изменение в имена серверов могут означать, что необходимо изменить имя SMTP-сервера как часть процесс публикации. This change in server names might mean you have to change the SMTP server name as part of your publishing process.
  • Номер порта, обычно — 25. The port number is usually 25. Тем не менее некоторые поставщики требуют использовать порт 587 или некоторых других портов. However, some providers require you to use port 587 or some other port.
  • Убедитесь, что используется правильные учетные данные. Make sure that you use the right credentials. Если вы опубликовали свой сайт у поставщика услуг размещения, используйте учетные данные, которые поставщик указал специально предназначены для электронной почты. If you’ve published your site to a hosting provider, use the credentials that the provider has specifically indicated are for email. Это может отличаться от учетных данных, используемых для публикации. These might be different from the credentials you use to publish.
  • Иногда вообще не требуются учетные данные. Sometimes you don’t need credentials at all. При отправке электронной почты с помощью ваш поставщик услуг Интернета, поставщика электронной почты могут уже знать свои учетные данные. If you’re sending email using your personal ISP, your email provider might already know your credentials. После публикации, может потребоваться использовать другие учетные данные, чем при тестировании на локальном компьютере. After you publish, you might need to use different credentials than when you test on your local computer.
  • Если поставщика электронной почты использует шифрование, необходимо установить WebMail.EnableSsl для true . If your email provider uses encryption, you have to set WebMail.EnableSsl to true .

Запустите EmailRequest.cshtml страницу в браузере. Run the EmailRequest.cshtml page in a browser. (Убедитесь, что выбран страницы файлы рабочей области, прежде чем запускать его.) (Make sure the page is selected in the Files workspace before you run it.)

Введите свое имя и описание проблемы, а затем нажмите кнопку отправить кнопки. Enter your name and a problem description, and then click the Submit button. Вы будете перенаправлены ProcessRequest.cshtml страницу, подтверждает ваше сообщение и который отправляет сообщение электронной почты. You’re redirected to the ProcessRequest.cshtml page, which confirms your message and which sends you an email message.

Отправка файла с помощью электронной почты Sending a File Using Email

Вы также можете отправлять файлы, вложенные в сообщения электронной почты. You can also send files that are attached to email messages. В этой процедуре вы создадите к текстовому файлу и две страницы HTML. In this procedure, you create a text file and two HTML pages. Текстовый файл будет использоваться как вложения электронной почты. You’ll use the text file as an email attachment.

На веб-сайте, добавьте новый текстовый файл и назовите его MyFile.txt. In the website, add a new text file and name it MyFile.txt.

Скопируйте следующий текст и вставьте его в файле: Copy the following text and paste it in the file:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Создание страницы с именем SendFile.cshtml и добавьте следующую разметку: Create a page named SendFile.cshtml and add the following markup:

Создание страницы с именем ProcessFile.cshtml и добавьте следующую разметку: Create a page named ProcessFile.cshtml and add the following markup:

Изменить связанные параметры в коде из примера, электронной почты следующее: Modify the following email related settings in the code from the example:

  • Задайте your-SMTP-host имя SMTP-сервера, у вас есть доступ к. Set your-SMTP-host to the name of an SMTP server that you have access to.
  • Задайте your-user-name-here имени пользователя для учетной записи сервера SMTP. Set your-user-name-here to the user name for your SMTP server account.
  • Задайте your-email-address-here на адрес электронной почты. Set your-email-address-here to your own email address. Это адрес электронной почты, которые отправляются сообщения. This is the email address that the message is sent from.
  • Задайте your-account-password на пароль для учетной записи сервера SMTP. Set your-account-password to the password for your SMTP server account.
  • Задайте target-email-address-here на адрес электронной почты. Set target-email-address-here to your own email address. (Как раньше, вы обычно отправляете сообщение электронной почты другому пользователю, но для тестирования, его можно отправить себе.) (As before, you’d normally send an email to someone else, but for testing, you can send it to yourself.)

Рекомендуем к прочтению

Добавить комментарий

Ваш адрес email не будет опубликован.