#asp.net #sql-server #email
Вопрос:
Я использую ASP.NET и SQL Server для отправки электронной почты нескольким получателям с циклом. Но здесь есть ошибка. Я нашел свое решение в Интернете, но все еще не могу его решить.
Вот показанная ошибка:
var toAddress = mm.To.Add(email);
Вот мой .aspx
код файла:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="push_notification_admin.aspx.cs" Inherits="Assignment.push_notification_admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function alertme() {
Swal.fire(
"The Email Successfully Sent!" ,
'success'
)
}
</script>
<style>
.error {
color: red;
background-image: url("../images/error.png");
background-repeat: no-repeat;
padding-left: 20px;
font-size: 12px;
}
.auto-style1 {
height: 33px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Push Notification:</h2>
<div>
<table style="width: 100%;">
<tr>
<td>amp;nbsp;<asp:Label ID="Label2" runat="server" Text="Subject"></asp:Label></td>
<td>amp;nbsp;<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter subjuct!" ControlToValidate="TextBox1" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style1"><asp:Label ID="Label1" runat="server" Text="Content"></asp:Label></td>
<td class="auto-style1"><asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter content!" ControlToValidate="TextBox2" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>amp;nbsp;<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /></td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
Вот мой aspx.cs
код файла:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Configuration;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Collections;
using System.Net.Security;
namespace Assignment
{
public partial class push_notification_admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * from Notification", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
ArrayList emailArray = new ArrayList();
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
while (reader.Read()){
emailArray.Add(reader["Notice_email"]);
}
foreach (string email in emailArray) {
using (MailMessage mm = new MailMessage(smtpSection.From, "sender@gmail.com"))
{
// Gmail Address from where you send the mail
var fromAddress = "inpuzzle2021@gmail.com";
// any address where the email will be sending
var toAddress = mm.To.Add(email);
//Password of your gmail address
const string fromPassword = "inpuzzlepwd";
// Passing the values and make a email formate to display
string subject = TextBox1.Text.ToString();
string body = TextBox2.Text.ToString();
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
}
reader.Close();
con.Close();
}
}
}
Я буду признателен, если кто-нибудь сможет помочь мне решить эту проблему.
Комментарии:
1. В чем заключается ошибка и где она возникает?
2. Не могли бы вы объяснить, в чем именно заключается ошибка, которую вы получаете, вы не упомянули подробности об ошибке, если вы обновите соответствующие сведения, то другим будет легко вам помочь.
Ответ №1:
Добавьте метод мм.To является пустым. т. е. метод ничего не возвращает, и, следовательно, вы не можете назначить его переменной. поэтому ваш код должен быть справедливым mm.To.Add(email);
. Это должно исправить ошибку, которую вы видите.
Комментарии:
1. Привет, я попробовал, но произошла еще одна ошибка, Вот строка: smtp.Отправить(с адреса, по адресу, тема, тело); «Адрес» подчеркнут красным
Ответ №2:
Вот последняя версия кода, и я решил ее! Кодировка, которую я изменяю, чтобы исправить это: emailArray.Добавить(читатель[«Notice_email»].toString()); и var toAddress = адрес электронной почты;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Configuration;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Collections;
using System.Net.Security;
namespace Assignment
{
public partial class push_notification_admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * from Notification", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
ArrayList emailArray = new ArrayList();
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
while (reader.Read()){
emailArray.Add(reader["Notice_email"].ToString());
}
foreach (string email in emailArray) {
using (MailMessage mm = new MailMessage(smtpSection.From, "sender@gmail.com"))
{
// Gmail Address from where you send the mail
var fromAddress = "inpuzzle2021@gmail.com";
// any address where the email will be sending
var toAddress = email;
//Password of your gmail address
const string fromPassword = "inpuzzlepwd";
// Passing the values and make a email formate to display
string subject = TextBox1.Text.ToString();
string body = TextBox2.Text.ToString();
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
}
reader.Close();
con.Close();
}
}
}