请查看以下代码
Email.h
#pragma once
#include <string>
using namespace System::Net;
using namespace System::Net::Mail;
using namespace System::Net::Mime;
using namespace std;
ref class Email
{
public:
Email();
//Sets the location of the attachment
void setAttachment(System::String ^attachmentLocation);
//Set the the from address of the email
void setFromAddress(System::String ^fromAddress);
//Set the reception's address of the email
void setToAddress(System::String ^toAddress);
//Set the subject pf the email
void setSubject(System::String ^subject);
//Set the Message of the email
void setMessage(System::String ^emailMessage);
//Set the SMTP client
void setSMTPClient(System::String ^smtpClient);
//Send the email
void sendEmail();
private:
MailMessage ^mail;
Attachment ^attachment;
SmtpClient ^client;
};
Email.cpp
#include "StdAfx.h"
#include "Email.h"
Email::Email()
{
mail = gcnew MailMessage();
}
void Email::setAttachment(System::String ^attachmentLocation)
{
attachment = gcnew Attachment(attachmentLocation);
ContentDisposition ^disposition = attachment->ContentDisposition;
disposition->CreationDate = System::IO::File::GetCreationTime(attachmentLocation);
disposition->ModificationDate = System::IO::File::GetLastWriteTime(attachmentLocation);
disposition->ReadDate = System::IO::File::GetLastAccessTime(attachmentLocation);
}
void Email::setFromAddress(System::String ^fromAddress)
{
mail->From = gcnew MailAddress(fromAddress);
}
void Email::setMessage(System::String ^emailMessage)
{
mail->Body = emailMessage;
}
void Email::setSMTPClient(System::String ^smtpClient)
{
client = gcnew SmtpClient(smtpClient);
}
void Email::setSubject(System::String ^subject)
{
mail->Subject = subject;
}
void Email::setToAddress(System::String ^toAddress)
{
mail->To->Add(toAddress);
}
void Email::sendEmail()
{
try
{
client->Send(mail);
}
catch(System::Exception ^e)
{
System::Windows::Forms::MessageBox::Show(e->ToString());
}
}
这就是我在另一个类
中调用此类的方法Email ^email = gcnew Email();
email->setToAddress("sss@yahoo.com");
email->setSubject("Intruder Detected");
email->setSMTPClient("localhost");
email->setMessage("sending mail. Image is attached");
email->setFromAddress("justsomemail@lol.com");
email->setAttachment("D:/OpenCV Final Year/Images/intruder.bmp");
email->sendEmail();
请注意,此处的From
地址是非现有/非真实地址。在实际代码中也是如此。 To
地址是真实的,并在此修改,因为我无法发布原始地址。
当我运行此代码时,我收到以下错误。
这是我第一次尝试使用C ++ / CLI(C ++和C#)发送电子邮件。我记得我在Java Mail中使用localhost
作为我的Java应用程序,所以我真的无法在这里找到真正的错误。