6 Replies - 10036 Views - Last Post: 08 December 2012 - 08:10 PM

#1 gfcf14  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 90
  • Joined: 19-January 11

Debug assertion sending emails in Visual C++ Windows forms program

Posted 04 December 2012 - 05:23 PM

Hi dreamincode! I have been doing a program in C++ for my final project. The program is supposed to help teens decide on what to text, and once the text message is prepared, to send it using email SMTP and SMS Gateways. I've used the code on this page ( http://www.emailarch...mail/kb/vc.aspx ) to send SMS through visual C+:

#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    // Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");
    
    // Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    
    // Set email subject
    oSmtp->Subject = _T("simple email from Visual C++ project");
    
    // Set email body
    oSmtp->BodyText = _T("this is a test email sent from Visual C++ project, do not reply");
    
    // Your SMTP server address
    oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
    
    // User and password for ESMTP authentication, if your server doesn't 
    // require User authentication, please remove the following codes.
    oSmtp->UserName = _T("test@emailarchitect.net");
    oSmtp->Password = _T("testpassword");

    // If your smtp server requires SSL connection, please add this line
    // oSmtp->SSL_init();

    _tprintf(_T("Start to send email ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}



But this program uses a win32 console application to run properly; I tested it with my email and phone number and other required info and it works. Yet I need to get it to work for a Windows forms application, and simply pasting the code inside an action event (properly implementing the tlh and tli files it requires and installing easendmail, and the directives for easendmailobj.tlh and namespace) gave me the error:

fatal error C1189: #error : comdef h header cannot be included under clr safe or clr pure


So I followed the advice in this page ( http://social.msdn.m...b0-79e4cf35c5ff ) and went to Properties->Common Language Runtime Support, and changed it to (/clr). I didn't get C1189 anymore, but I still had to convert the System strings to standard strings, so I used the code from this page ( http://stackoverflow...ng-to-stdstring , the one that has 20 points) to convert, then wrote down the code to send emails in a header file:

#pragma once

#include <string>
#include <iostream>
#include <sstream>
#include <tchar.h>

#include "easendmailobj.tlh"

using namespace EASendMailObjLib;
using namespace std;

class TextMessage
{
	private:
		string email;
		string pass;
		string phone;
		string subject;
		string message;
		string smtp;
	public:
		TextMessage::TextMessage(string email, string pass, string phone, string subject, string message, string smtp)
		{
			this->email = email;
			this->pass = pass;
			this->phone = phone;
			this->subject = subject;
			this->message = message;
			this->smtp = smtp;
		}

		string send()
		{
			::CoInitialize( NULL );

			IMailPtr oSmtp = NULL;
			oSmtp.CreateInstance( "EASendMailObj.Mail");
			oSmtp->LicenseCode = _T("TryIt");
    
			// Set your sender email address
			oSmtp->FromAddr = email.c_str();
    
			// Add recipient email address
			oSmtp->AddRecipientEx(phone.c_str(), 0 );
    
			// Set email subject
			oSmtp->Subject = subject.c_str();
    
			// Set email body
			oSmtp->BodyText = message.c_str();
    
			// Your SMTP server address
			oSmtp->ServerAddr = smtp.c_str();
    
			// User and password for ESMTP authentication, if your server doesn't 
			// require User authentication, please remove the following codes.
			oSmtp->UserName = email.c_str();
			oSmtp->Password = pass.c_str();

			// If your smtp server requires SSL connection, please add this line
			// oSmtp->SSL_init();

			//_tprintf(_T("Start to send email ...\r\n" ));
  
			if( oSmtp->SendMail() == 0 )
			{
				return "Email was sent successfully!\n";//_tprintf( _T("email was sent successfully!\r\n"));
			}
			else
			{
				stringstream s;
				s << "Failed to send email with the following error:\n\n";
				s << (const TCHAR*)oSmtp->GetLastErrDescription();
				/*_tprintf( _T("failed to send email with the following error: %s\r\n"),
					(const TCHAR*)oSmtp->GetLastErrDescription());*/
				string ss = s.str();

				return ss;
			}

			if( oSmtp != NULL )
				oSmtp.Release();

			//return 0;
		}

		TextMessage(void){}

		~TextMessage(void){}
};



And added #include <tchar.h> because for some reason _T() was not recognized. So the difference between

oSmtp->FromAddr = email.c_str();



and

oSmtp->FromAddr = _T("test@emailarchitect.net");



is that I couldn't conceal the string email inside _T(email) because I got

error C2065: 'Lemail' : undeclared identifier



so to use the email string and all the others without code errors I wrote it as

oSmtp->FromAddr = email;



but then I got this error:

error C2664: 'EASendMailObjLib::IMail::PutFromAddr' : cannot convert parameter 1 from 'std::string' to '_bstr_t'



so I instead made email a constant string (email.c_str()) and I got no errors there. However as I run the program, I get the following:

Debug Assertion Failed!

Program:

...nal\TeenageTextingAssistant\Debug\TeenageTextingAssistant.exe
File f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c
Line: 1516

Expression: _CrtIsValidHeapPointer(pUserData)



The line it refers to is this:

_ASSERTE(_CrtIsValidHeapPointer(pUserData));



I went to check the output of the program, and i get:

'TeenageTextingAssistant.exe': Loaded 'E:\Advanced C++\Final\TeenageTextingAssistant\Debug\TeenageTextingAssistant.exe', Symbols loaded.
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\ntdll.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\mscoree.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\kernel32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\KernelBase.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\msvcr100d.dll', Symbols loaded.
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\msvcp100d.dll', Symbols loaded.
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\ws2_32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\msvcrt.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\rpcrt4.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\sspicli.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\cryptbase.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\sechost.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\nsi.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\winmm.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\user32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\gdi32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\lpk.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\usp10.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\advapi32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\ole32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\oleaut32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\imm32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\msctf.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscoreei.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\shlwapi.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\msvcr100_clr0400.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\assembly\NativeImages_v4.0.30319_32\mscorlib\16126cae96ea2422253ae06eeb672abc\mscorlib.ni.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\uxtheme.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Program Files (x86)\Lenovo\Onekey Theater\ActiveDetect32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Program Files (x86)\Lenovo\Onekey Theater\WindowsApiHookDll32.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\version.dll', Cannot find or open the PDB file
The thread 'Win32 Thread' (0x1080) has exited with code 0 (0x0).
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\nlssorting.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe' (Managed (v4.0.30319)): Loaded 'E:\Advanced C++\Final\TeenageTextingAssistant\Debug\TeenageTextingAssistant.exe', Symbols loaded.
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\clrjit.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\diasymreader.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\assembly\NativeImages_v4.0.30319_32\System\811a7bc79f8f0a5be8065292a320819e\System.ni.dll', Cannot find or open the PDB file
'TeenageTextingAssistant.exe' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
First-chance exception at 0x77871985 in TeenageTextingAssistant.exe: 0xC0000005: Access violation reading location 0xe29652a7.
'TeenageTextingAssistant.exe': Loaded 'C:\Windows\SysWOW64\dwmapi.dll', Cannot find or open the PDB file
First-chance exception at 0x59447009 (msvcr100d.dll) in TeenageTextingAssistant.exe: 0xC0000005: Access violation reading location 0xe29652bc.
First-chance exception at 0x753dc41f in TeenageTextingAssistant.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000..
An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module.

Additional information: The type initializer for '<Module>' threw an exception.

An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module.

Additional information: The type initializer for '<Module>' threw an exception.

The thread 'Win32 Thread' (0x1040) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0xcac) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x1088) has exited with code 0 (0x0).
The program '[3116] TeenageTextingAssistant.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).
The program '[3116] TeenageTextingAssistant.exe: Native' has exited with code 0 (0x0).



While when I try to build the solution, I get:

1>------ Rebuild All started: Project: TeenageTextingAssistant, Configuration: Debug Win32 ------
1>  stdafx.cpp
1>  AssemblyInfo.cpp
1>  TeenageTextingAssistant.cpp
1>  Generating Code...
1>  .NETFramework,Version=v4.0.AssemblyAttributes.cpp
1>  TeenageTextingAssistant.vcxproj -> E:\Advanced C++\Final\TeenageTextingAssistant\Debug\TeenageTextingAssistant.exe
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========



Is it normal for the program not to find the pdb files? Also, the code I use to call the TextMessage header file is:

string email, pass, phone, smtp, mess;

msclr::interop::marshal_context context;

email = context.marshal_as<std::string>(yemtbox->Text);
pass = context.marshal_as<std::string>(passtbox->Text);
smtp = context.marshal_as<std::string>(smtps[emprovcbox->SelectedIndex]);

String^ sphone = /*L"" +*/ phonetbox->Text + "@" + smsgs[carcbox->SelectedIndex];
phone = context.marshal_as<std::string>(sphone);

mess = context.marshal_as<std::string>(msbox->Text);

TextMessage tm(email, pass, phone, "TTA sent message", mess, smtp);

stringstream s;
s << tm.send();
string ss = s.str();
String^ sss = gcnew String(ss.c_str());
textLabel->Text = L"" + sss;



Sorry if it's long, but I wanted to explain everything I did in case there's a problem somewhere. I've searched and there's supposed to be another way of sending emails in a windows form project ( http://msdn.microsof...smtpclient.aspx ), yet I hardly understand the code they give, or what directives should be used. Am I doing this the right way or is all the code I posted above too redundant or unnecessary? If so what is a simpler way to send emails through a Windows forms application? Thank you for any replies in advance

This post has been edited by gfcf14: 04 December 2012 - 05:24 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Debug assertion sending emails in Visual C++ Windows forms program

#2 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3485
  • View blog
  • Posts: 10,742
  • Joined: 05-May 12

Re: Debug assertion sending emails in Visual C++ Windows forms program

Posted 04 December 2012 - 06:15 PM

Quote

Is it normal for the program not to find the pdb files?


Yes, it is normal. If you want, you can download symbols from the symbol server, but typically, its usually more useful when you are doing system level debugging rather than app level debugging.

If you are using WinForms, I recommend using the managed SmtpClient object, but that is assuming that you only need to send SMTP mail, and are not dependent on support from the current ActiveX object that you are using to also do SMS messaging.

Now, as for the assert you are seeing, you need to post the full callstack since what you currently posted doesn't really show us what is causing the C runtime library to find the heap as being invalid.
Was This Post Helpful? 0
  • +
  • -

#3 gfcf14  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 90
  • Joined: 19-January 11

Re: Debug assertion sending emails in Visual C++ Windows forms program

Posted 04 December 2012 - 06:36 PM

Thanks for your help, but where do I find the callstack? I've never had problems of this kind so I wouldn't know...

And the only thing I wish to do with this program is SMS messaging, no MMS, just the very basics. What (header files and the like) would I need to use SmtpClient?
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3485
  • View blog
  • Posts: 10,742
  • Joined: 05-May 12

Re: Debug assertion sending emails in Visual C++ Windows forms program

Posted 04 December 2012 - 07:07 PM

You don't need any headers to use SmtpClient. Just add using namespace System::Net::Mail. See the C++ sample code that you originally linked to: http://msdn.microsof...#code-snippet-1

As for the callstack, when the alert comes selection the option to break. Then when the debugger comes up, choose Debug.Callstack.
Was This Post Helpful? 1
  • +
  • -

#5 gfcf14  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 90
  • Joined: 19-January 11

Re: Debug assertion sending emails in Visual C++ Windows forms program

Posted 05 December 2012 - 03:10 PM

I pretty much copied and pasted the code at http://msdn.microsof...#code-snippet-1 and changed the values of the variables to match the ones I'm using, and it runs well. Yet when I get to the part to press the button to send the message, I get:

An unhandled Exception of type 'System.Net.Mail.SmtpException' occurred in System.dll

Additional information: The SMTP host was not found.



However, I'm providing the smtp host (smtp.mail.yahoo.com). But I must too mention I'm doing this connected to MDC's (Miami Dade College Kendall Campus) network. And the previous program I tried (the one I mention in the question, using the code at http://www.emailarch...mail/kb/vc.aspx ) did run AT HOME, yet it also couldn't find the SMTP, giving me the error:

failed to send email with the following error: Error with connecting server; current server: smtp.mail.yahoo.com; connect failed, error: 0x0000274c



I probably have the program running already, but I might have to present it to my class. And although I can probably tell them the college's network blocks connections to servers, do you happen to know how I can override this to get my message to be sent? Thank you
Was This Post Helpful? 0
  • +
  • -

#6 gfcf14  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 90
  • Joined: 19-January 11

Re: Debug assertion sending emails in Visual C++ Windows forms program

Posted 05 December 2012 - 09:57 PM

I've run the program at home, and although I get no errors, the message is not sent. Is it that the function SendCompletedCallback() ( http://msdn.microsof...#code-snippet-1 ) is not being called properly (or not called at all) ? I put that function around the top of the Form1.h :

#include <cstring>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <WinSock2.h>
#include <Windows.h>
#include <msclr\marshal_cppstd.h>

#include "TextMessage.h"

#pragma once

using namespace System::Net::Mail;

namespace TeenageTextingAssistant {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;
	using namespace std;

	/// <summary>
	/// Summary for Form1
	/// </summary>
	
	
	

	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:

		static void SendCompletedCallback(Object^ sender, AsyncCompletedEventArgs^ e)
		{
			// Get the unique identifier for this asynchronous  
			// operation.
			String^ token = (String^) e->UserState;

			if (e->Cancelled)
			{
				Console::WriteLine("[{0}] Send canceled.", token);
			}
			if (e->Error != nullptr)
			{
				Console::WriteLine("[{0}] {1}", token, 
					e->Error->ToString());
			} else
			{
				Console::WriteLine("Message sent.");				
			}
			mailSent = true;
		}



And the rest of the code inside the continue button's press event:

String^ sphone = phonetbox->Text + smsgs[carcbox->SelectedIndex];

 // Command line argument must the the SMTP host.
					SmtpClient^ client = gcnew SmtpClient(smtps[emprovcbox->SelectedIndex]);
					// Specify the e-mail sender. 
					// Create a mailing address that includes a UTF8  
					// character in the display name.
					MailAddress^ from = gcnew MailAddress(yemtbox->Text,
						"User " + (wchar_t)0xD8 + " Name",
						System::Text::Encoding::UTF8);
					// Set destinations for the e-mail message.
					MailAddress^ to = gcnew MailAddress(sphone);
					// Specify the message content.
					MailMessage^ message = gcnew MailMessage(from, to);
					message->Body = msbox->Text;
					// Include some non-ASCII characters in body and  
					// subject.
					String^ someArrows = gcnew String(gcnew array<wchar_t>{L'\u2190', 
						L'\u2191', L'\u2192', L'\u2193'});
					message->Body += Environment::NewLine + someArrows;
					message->BodyEncoding = System::Text::Encoding::UTF8;
					message->Subject = "TTA sent message!" + someArrows;
					message->SubjectEncoding = System::Text::Encoding::UTF8;
					// Set the method that is called back when the send 
					// operation ends.
					client->SendCompleted += gcnew
						SendCompletedEventHandler(SendCompletedCallback);
					// The userState can be any object that allows your  
					// callback method to identify this send operation. 
					// For this example, the userToken is a string constant.
					String^ userState = "test message1";
					client->SendAsync(message, userState);
					/*Console::WriteLine("Sending message... press c to" +
						" cancel mail. Press any other key to exit.");
					String^ answer = Console::ReadLine();
					// If the user canceled the send, and mail hasn't been  
					// sent yet,then cancel the pending operation. 
					if (answer->ToLower()->StartsWith("c") && mailSent == false)
					{
						client->SendAsyncCancel();
					}*/
					// Clean up. 
					delete message;
					client = nullptr;
					//Console::WriteLine("Goodbye.");



Also, how can I possibly set the text of a label in the display (called textLabel) to the text generated in the if statements of SendCompletedCallback (the ones in Console::Writeline) ? Whenever I put textLabel->Text there, I get "left of ->Text must point to class/struct/union. Am I putting the SendCompletedCallback function in the wrong place? Is it ok where it is or should it be after some line of code? Thank you again
Was This Post Helpful? 0
  • +
  • -

#7 gfcf14  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 90
  • Joined: 19-January 11

Re: Debug assertion sending emails in Visual C++ Windows forms program

Posted 08 December 2012 - 08:10 PM

Thank you for your help, Skydiver. I've been looking further into other pages from microsoft, and found this one http://msdn.microsof...y/swas0fwc.aspx , which though more concise, it's easier in the noggin to understand. To actually get the messages to send (I believe this was missing from the previous code I used), I needed to add credentials in the following form:

client->Credentials = gcnew NetworkCredential(username, password);


Now if I am able to know how to let the message through a college network I'd get an A++

Will someone (possibly who stumbled upon this same issue and found this page) PLEASE grant me my first reputation point? Pretty please??
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1