Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Сети > Отправка Email .net


Автор: bigbuka 24.7.2010, 18:11
Добрый день...
пытаюь отправить письмо  вот такой функцией взятой с MSDN 
Код

static void CreateMessageWithAttachment(std::string File)
   {
     String^ server=gcnew String("smtp.gmail.com");
      // Specify the file to be attached and sent.
      // This example assumes that a file named Data.xls exists in the
      // current working directory.
     String^ file=gcnew String(File.c_str());

      // Create a message and set up the recipients.
      MailMessage^ message = gcnew MailMessage( L"[email protected]",L"[email protected]",L"Dll report.",L"Dll is inside" );

      // Create  the file attachment for this e-mail message.
      Attachment^ data = gcnew Attachment(file, MediaTypeNames::Application::Octet);

      // Add time stamp information for the file.
      ContentDisposition^ disposition = data->ContentDisposition;
      disposition->CreationDate = System::IO::File::GetCreationTime( file );
      disposition->ModificationDate = System::IO::File::GetLastWriteTime( file );
      disposition->ReadDate = System::IO::File::GetLastAccessTime( file );

      // Add the file attachment to this e-mail message.
      message->Attachments->Add( data );

      //Send the message.
      SmtpClient^ client = gcnew SmtpClient( server,25 );

      // Add credentials if the SMTP server requires them.
      client->Credentials = gcnew System::Net::NetworkCredential("[email protected]", "1234567");
      //client->Credentials = new CredentialCache::DefaultNetworkCredentials;
      client->Send( message );

      // Display the values in the ContentDisposition for the attachment.
      ContentDisposition^ cd = data->ContentDisposition;
      Console::WriteLine( L"Content disposition" );
      Console::WriteLine( cd );
      Console::WriteLine( L"File {0}", cd->FileName );
      Console::WriteLine( L"Size {0}", cd->Size );
      Console::WriteLine( L"Creation {0}", cd->CreationDate );
      Console::WriteLine( L"Modification {0}", cd->ModificationDate );
      Console::WriteLine( L"Read {0}", cd->ReadDate );
      Console::WriteLine( L"Inline {0}", cd->Inline );
      Console::WriteLine( L"Parameters: {0}", cd->Parameters->Count );
      IEnumerator^ myEnum1 = cd->Parameters->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum1->Current);
         Console::WriteLine( L"{0} = {1}", d->Key, d->Value );
      }

      data->~Attachment();
      client->~SmtpClient();
   }

при отправке появляеся exeption :
 Серверу SMTP требовалось защищенное соединение, или подлинность клиента не была установлена. Ответ сервера: 5.7.0 Must issue a STARTTLS command first. p2sm544725fak.46

Автор: bigbuka 24.7.2010, 18:43
все проблему решил исправив вот так
Код

  client->Credentials = gcnew System::Net::NetworkCredential("[email protected]", "1234567");
 client->EnableSsl=true;


Автор: Буратиныч 24.3.2011, 12:20
Сорри за новичковский вопрос, но что нужно указывать в заголовке, чтобы идентификаторы определялись?

Это также касается и вот этого кода:
Код

void sendMail(char from, string to, string cc, string bcc, string subject, string body)
{
    //Отсылка через System.Web.Mail
    // Mail initialization
    System.Web.Mail.MailMessage mailMsg = new System.Web.Mail.MailMessage();
    mailMsg.From = from;
    mailMsg.To = to;
    mailMsg.Cc = cc;
    mailMsg.Bcc = bcc;
    mailMsg.Subject = subject;
    mailMsg.BodyFormat = System.Web.Mail.MailFormat.Text;
    mailMsg.Body = body;
    mailMsg.Priority = System.Web.Mail.MailPriority.High;
    mailMsg.Attachments.Add(new MailAttachment("c:\test.txt");

    // Smtp configuration
    System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com";//smtp is :smtp.gmail.com
    // - smtp.gmail.com use smtp authentication
    mailMsg.Fields.Add("", "1");
    mailMsg.Fields.Add("", "[email protected]");
    mailMsg.Fields.Add("", "mypassword");
    // - smtp.gmail.com use port 465 or 587
    mailMsg.Fields.Add("", "465");//port is: 465, 25 default
    // - smtp.gmail.com use STARTTLS (some call this SSL)
    mailMsg.Fields.Add("", "true");
    // try to send Mail

    try
    {
        System.Web.Mail.SmtpMail.Send(mailMsg);
        return "";
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

Автор: Буратиныч 24.3.2011, 13:34
Если можно, напишите как должен выглядеть исходник полностью, а то я уже запутался в декларациях.

Добавлено через 1 минуту и 54 секунды
Вот ещё образец, но не знаю как его правильно применить  smile 
http://www.digitalcoding.com/Code-Snippets/CPP-CLI/C-CLI-Code-Snippet-Send-Email-Using-SMTP-Server.html

Автор: Буратиныч 24.3.2011, 17:03
Вот ещё вроде как так можно, но это какой-то имхо более старый вариант, и я не знаю как тут приаттачить файл.  Люди, помогите ламеру!

Код

WSADATA ws;
SOCKET s;
struct sockaddr_in addr;
hostent *d_addr;
char text[512];
int main()
{
(WSAStartup (MAKEWORD( 1,1 ), &ws));
s = socket (AF_INET, SOCK_STREAM, 0);
d_addr = gethostbyname ("smtp.yandex.ru"); 
addr.sin_family = AF_INET; 
addr.sin_addr.s_addr = *((unsigned long *) d_addr->h_addr);
addr.sin_port = htons (25);
if (SOCKET_ERROR == (connect (s, (sockaddr *) &addr,
sizeof (addr)))) 

printf("Error in connect(...)\n");
return 1; }
recv(s,text,sizeof(text),0);
strcpy(text,"EHLO smtp.yandex.ru\r\n");
send(s,text,strlen(text),0);
recv(s,text,sizeof(text),0);
strcpy(text,"AUTH login\r\n");
send(s,text,strlen(text),0);
recv(s,text,sizeof(text),0);
strcpy(text,"Ëîãèí â base64\r\n");
send(s,text,strlen(text),0);
recv(s,text,sizeof(text),0);
strcpy(text,"Ïàðîëü â base64\r\n");
send(s,text,strlen(text),0);
recv(s,text,sizeof(text),0);
strcpy(text,"MAIL FROM: [email protected]\r\n");
send(s,text,strlen(text),0);
recv(s,text,sizeof(text),0);
strcpy(text,"RCPT TO: [email protected]\r\n");
send(s,text,strlen(text),0);
recv(s,text,sizeof(text),0);
strcpy(text,"DATA\r\n");
send(s,text,strlen(text),0);
recv(s,text,sizeof(text),0);
strcpy(text,"FROM: [email protected]\r\n");
send(s,text,strlen(text),0);
strcpy(text,"TO: [email protected]\r\n");
send(s,text,strlen(text),0);
strcpy(text,"SUBJECT: òåìà\r\n");
send(s,text,strlen(text),0); 
strcpy(text,"Ñîîáùåíèå\n");
send(s,text,strlen(text),0);
strcpy(text,"\r\n.\r\n");
send(s,text,strlen(text),0);
recv(s,text,sizeof(text),0);
strcpy(text,"QUIT");
send(s,text,strlen(text),0);
closesocket(s);
return 0;
}


Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)