2016-03-28 3 views
-2

Мне было интересно, может ли кто-нибудь помочь мне. У меня есть простая таблица Suppliers, в которой есть адреса электронной почты для моих поставщиков.Мне нужно пройти через адреса электронной почты в таблице в базе данных SQL Server и все Email

Мне нужно прокрутить адреса электронной почты «SuppEmail» в таблице Suppliers в базе данных SQL Server SpecCars и отправить им все по электронной почте.

Я был у него в течение нескольких дней теперь, глядя на линии и пытаемся много различных вариантов, но независимо от того, что я делаю, он отправляет только один адрес электронной почты к первой записи [email protected] в таблице, и это его ,

Если бы вы могли помочь, это было бы фантастически. Это решение ASP.NET C#.

Это Suppliers стол, он просто имеет две записи в них:

CREATE table Suppliers 
(
    SuppId  INT IDENTITY(1,1) PRIMARY KEY, 
    SuppName NVARCHAR(60)  NOT NULL, 
    SuppAddress NVARCHAR(150)  NOT NULL, 
    SuppSuburb NVARCHAR(60)  NOT NULL, 
    SuppState NVARCHAR(30)  NOT NULL, 
    SuppPost NVARCHAR(10)  NOT NULL, 
    SuppPhone NVARCHAR(10)  NOT NULL, 
    SuppEmail NVARCHAR(100)  NOT NULL, 
    SuppCode NVARCHAR(10)  NOT NULL 
) 

Insert into Suppliers (SuppName, SuppAddress, SuppSuburb, SuppState, SuppPost, SuppPhone, SuppEmail, SuppCode) 
values ('Jacks Auto', '2 Jill Street', 'Belgrade', 'VIC', '3299', '9555 4457', '[email protected]', 'JACBLA') 

Insert into Suppliers (SuppName, SuppAddress, SuppSuburb, SuppState, SuppPost, SuppPhone, SuppEmail, SuppCode) 
values ('Ultimate Lights', '205 Browns Road', 'Tullamarine', 'VIC', '3011', '9877 2255', '[email protected]', 'ULTTUL') 

Это фрагмент кода:

SqlDataReader sqlData; 
    SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=SpecCars;Integrated Security=True"); 

    connection.Open(); 
    sqlData = new SqlCommand("Select SuppEmail From Suppliers", connection).ExecuteReader(); 

    int count = sqlData.FieldCount; 

    while (sqlData.Read()) 
    { 
    for (int i = 0; i < count; i++) 
    { 
     string emailnew = sqlData[i].ToString(); 

     MailMessage mailMessage = new MailMessage(); 

     mailMessage.From = new MailAddress("myemail.com"); 
     mailMessage.To.Add("myemail.com"); 
     mailMessage.To.Add(emailnew); 
     //mailMessage.CC.Add(emailnew); 
     mailMessage.Subject = "Assembly Line Stop"; 
     mailMessage.Priority = MailPriority.High; 

     mailMessage.Body = "Please be advised that the assembly line at Specialised Cars has STOPPED. You will be notified once the line has started again. Any Services between the LINE STOP and the LINE START will be carried out after 19:00 (7pm)."; 
     mailMessage.IsBodyHtml = true; 

     SmtpClient smtpClient = new SmtpClient("smtp-mail.myprovider.com", 587); 
     smtpClient.EnableSsl = true; 
     smtpClient.Credentials = new System.Net.NetworkCredential("myemail.com", "password"); 
     smtpClient.Send(mailMessage); 
    } 
} 
connection.Close(); 
+0

@chunk попытаться петлю только для добавления сообщений электронной почты, то exectue оставшейся части кода, как это .... – Webruster

+1

MailMessage MailMessage = новый MailMessage(); for (int i = 0; i Webruster

ответ

0
//----------------- 

//Hi All, just a quick update: 


//Trying8.aspx - Finally Works, it sends LINE STOP Email to every SuppEmail recipient in Suppliers Table 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Trying8.aspx.cs" Inherits="SpecCars.Admin.Trying8" %> 

<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> 
     <br /> 
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 
    </div> 
    </form> 
</body> 
</html> 

//----------------- 

//Trying8.aspx.cs - Finally Works, it sends LINE STOP Email to every SuppEmail recipient in Suppliers Table 

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Net; 
using System.Net.Mail; 
using System.Text; 

namespace SpecCars.Admin 
{ 
    public partial class Trying8 : System.Web.UI.Page 
    { 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 

     SqlDataReader sqlData; 
     SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=SpecCars;Integrated Security=True"); 
     connection.Open(); 

     sqlData = new SqlCommand("Select * From Suppliers", connection).ExecuteReader(); 
     using (SmtpClient smtpClient = new SmtpClient("smtp-mail.provider.com", 587)) 
     { 
     while (sqlData.Read()) 
     { 
      string emailnew = sqlData["SuppEmail"].ToString(); 
      Label1.Text = emailnew.ToString(); 

      using (MailMessage message = new MailMessage()) 
      { 
      try 
      { 
       message.From = new MailAddress("[email protected]"); 
       // This doesn't Send (To:) [email protected] 
       MailAddress AddressTo = new MailAddress("[email protected]"); 
       // This does Send (To:) to SuppEmail recipient in Suppliers Table 
       message.To.Add(emailnew); 
       //This does Send a (CC:) [email protected] 
       message.CC.Add("[email protected]"); 
       message.Subject = "Assembly Line Stop"; 
       message.Priority = MailPriority.High; 

       message.Body = "Please be advised that the assembly line at Specialised Cars has STOPPED. You will be notified once the line has started again. Any Services between the LINE STOP and the LINE START will be carried out after 19:00 (7pm)."; 
       message.IsBodyHtml = true; 

       smtpClient.EnableSsl = true; 
       smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "password"); 
       smtpClient.Send(message); 
       // smtpClient.Dispose(); 
       // message.Dispose(); 
      } 
      catch (Exception ex) 
      { 
       //log exceptions here, you can write it to a txt file, or to a label in your form for testing purpose 
       //we are trying to see if you get an exception.. 
       Label1.Text = ex.Message; 
      } 
      } 
     } 
     } 

    } 
    } 
} 

//----------------- 
0

Попробуйте это:

var mailMessage = CreateMessage(); 
using(var connection = new SqlConnection("Data Source=.;Initial Catalog=SpecCars;Integrated Security=True")) 
{ 
    connection.Open(); 
    using(var sqlData = new SqlCommand("Select SuppEmail From Suppliers", connection).ExecuteReader()) 
    { 
     while (sqlData.Read()) 
     { 
      mailMessage.Bcc.Add(emailnew); 
     } 
    } 
} 
SendMessage(mailMessage) 


private MailMessage CreateMessage() 
{ 
    var mailMessage = new MailMessage(); 
    mailMessage.From = new MailAddress("myemail.com"); 
    mailMessage.To.Add("myemail.com"); 

    mailMessage.Subject = "Assembly Line Stop"; 
    mailMessage.Priority = MailPriority.High; 

    mailMessage.Body = "Please be advised that the assembly line at Specialised Cars has STOPPED. You will be notified once the line has started again. Any Services between the LINE STOP and the LINE START will be carried out after 19:00 (7pm)."; 
    mailMessage.IsBodyHtml = true; 
    return mailMessage; 
} 

private void SendMessage(MailMessage mailMessage) 
{ 
    var smtpClient = new SmtpClient("smtp-mail.myprovider.com", 587); 
    smtpClient.EnableSsl = true; 
    smtpClient.Credentials = new System.Net.NetworkCredential("myemail.com", "password"); 
    smtpClient.Send(mailMessage); 
} 

Примечание: этот код может быть и должен быть лучше. Рассмотрим рефакторинг, чтобы получить параметры connectionstring и почты из web.config вместо того, чтобы их жестко закодировать в вашем приложении.

+0

Привет Зоар, Спасибо за это, я попытался вставить код в Баттона, но у меня есть красные волнистые линии под«BBC и emailnew»в«mailMessage.BCC.Add (emailnew);» строка Ошибка «System.Net.Mail.MailMessage» не содержит определения для «BCC», и метод расширения «BCC», принимающий первый аргумент типа, не найден и красную строку squiggly после ' SendMessage (mailMessage) 'строка Ошибка ; ожидается, когда я добавляю его, это бросок ошибки } ожидается \t и красной волнистой линии после последнего «}» Ошибка Тип или пространство имен определение, или с истекшим файла ожидаемого ли это можно проверить. – Chuck

+0

@ Чак извините, мой mistak. должен быть 'Bcc', а не' BCC'. Быстрый поиск дал бы вам [это.] (Https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.bcc (v = vs.110) .aspx) –

+0

Привет, Зоар , Я пробовал это и многое другое и все равно получаю те же ошибки. Не могли бы вы попробовать код и сообщить мне, если вы получите те же ошибки. – Chuck