Link to home
Start Free TrialLog in
Avatar of alecam
alecam

asked on

send email from visual basic

How can i send a email from visual basic?
I know that i can use the apis of windows, but i dont know how.
Avatar of alecam
alecam

ASKER

i want to do a form and send mail from there
ASKER CERTIFIED SOLUTION
Avatar of vinnyd79
vinnyd79

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here's an example using Outlook:

Dim olf As Outlook.MAPIFolder
Dim mail As Outlook.MailItem
Dim apOutlook As Outlook.Application
Dim contacts As Outlook.MAPIFolder
Dim distList As Outlook.DistListItem
Dim myAttachments As Outlook.Attachments
Dim myAttchment As Outlook.Attachment

Set apOutlook = New Outlook.Application
'apOutlook.Session.Logon ("VW Mail")
apOutlook.Session.Logon "Userid", "password"
Set olf = apOutlook.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set contacts = apOutlook.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts)

Set distList = contacts.Items("TestList")
Set mail = olf.Items.Add    ' New Mail Item
mail.Subject = "No Subject"
mail.Recipients.Add distList
Set myAttachments = mail.Attachments
Set myAttachment = myAttachments.Add("file.dat")
mail.Body = mail.Body & vbCrLf & "See Attachment(s)"
mail.Send
apOutlook.Session.Logoff

Hope this helps.
I'd be temped to use the Outlook objects if you've got Outlook installed, that way it handles a lot of the finicky stuff for you rather than messing with the Windows API.
Turn on Microsoft Outlook Vx Object Library under project references, then do stuff like:

Set myOlApp = CreateObject("Outlook.Application")
Set myNameSpace = myOlApp.GetNameSpace("MAPI")
Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myForward = myFolder.Items(1).Forward
myForward.Recipients.Add "Laura Jennings"
myForward.Send

OneEyedMan
you can do that with (Microsoft Winsock)
press (Ctrl+T ) and add (Microsoft Winsock)to your project..
then add winsock componnet on ur form ..(winsock1)
then put  7 textboxs, and name them as the following:

txtSMTP_Server
txtFromName
txtFromMail
txtToName
txtToMail
txtSubject
txtMsgBody
------------------------
in the delcare section of the form put this:

Private Enum SMTP_State
        MAIL_CONNECT
        MAIL_HELO
        MAIL_FROM
        MAIL_RCPTTO
        MAIL_DATA
        MAIL_DOT
        MAIL_QUIT
End Enum
Private m_State As SMTP_State
------------------------------------
Add command button (command1) and make its caption to: Send and this code in it:
 
 Winsock1.Close  ' This to close any exisiting connection
 Winsock1.Connect Trim$(txtSMTP_Server), 25  'Connect to the server
 m_State = MAIL_CONNECT 'Change the state of connection

----------------------------------------
Also you must add this in DataArrival of Winsock1:


Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim strServerResponse   As String
Dim strResponseCode     As String
Dim strDataToSend       As String
Dim m_strEncodedFiles As String
On Error Resume Next

    Winsock1.GetData strServerResponse
    strResponseCode = Left$(strServerResponse, 3)

    If strResponseCode = "250" Or _
       strResponseCode = "220" Or _
       strResponseCode = "354" Then
       
        Select Case m_State
            Case MAIL_CONNECT
                m_State = MAIL_HELO
                strDataToSend = Trim$(txtFromMail)
                strDataToSend = Left$(strDataToSend, _
                                InStr(1, strDataToSend, "@") - 1)

                Winsock1.SendData "HELO " & strDataToSend & vbCrLf

            Case MAIL_HELO
                m_State = MAIL_FROM
                Winsock1.SendData "MAIL FROM:" & Trim$(txtFromMail) & vbCrLf

            Case MAIL_FROM
                    m_State = MAIL_RCPTTO              
                    Winsock1.SendData "RCPT TO:" & Trim$(txtToMail) & vbCrLf

            Case MAIL_RCPTTO
                m_State = MAIL_DATA
                Winsock1.SendData "DATA" & vbCrLf
            Case MAIL_DATA
                m_State = MAIL_DOT
                '
                'So now we are sending a message body
                'Each line of text must be completed with
                'linefeed symbol (Chr$(10) or vbLf) not with vbCrLf
                '
                Winsock1.SendData "From:" & txtFromName & " <" & txtFromMail & ">" & vbCrLf

                Winsock1.SendData "To:" & txtToName & " <" & txtToMail & ">" & vbCrLf

                Winsock1.SendData "X-Mailer: VBMail Sender" & vbCrLf
                Winsock1.SendData "Mime-Version: 1.0" & vbCrLf
                Winsock1.SendData "Content-Type: text/" + "plain;" + vbTab + "charset=us-ascii" + vbCrLf

                Winsock1.SendData "Subject:" & txtSubject & vbLf & vbCrLf
                '
                '
                Dim varLines    As Variant
                Dim varLine     As Variant
                Dim strMessage  As String
               
                strMessage = txtMsgBody & vbCrLf & vbCrLf & m_strEncodedFiles

                m_strEncodedFiles = ""                 

                'Parse message to get lines (for VB6 only)
                varLines = Split(strMessage, vbCrLf)
                'clear memory
                strMessage = vbNullString
                '
                'Send each line of the message
                For Each varLine In varLines
                    Winsock1.SendData CStr(varLine) & vbLf
                Next
                '
                'Send a dot symbol to inform server
                'that sending of message comleted

                Winsock1.SendData vbCrLf & "." & vbCrLf

            Case MAIL_DOT
                m_State = MAIL_QUIT
                '
                'Send QUIT command to the server
                Winsock1.SendData "QUIT" & vbCrLf
                '
            Case MAIL_QUIT
                '
                'Close connection
                Winsock1.Close                

        End Select
       
    Else
        '
        'If we are here server replied with
        'unacceptable respose code therefore we need
        'close connection and inform user about problem
        '
        Winsock1.Close
        '
        If Not m_State = MAIL_QUIT Then
            MsgBox "SMTP Error: " & strServerResponse, _
                    vbInformation, "SMTP Error"
        Else
            MsgBox "Message sent successfuly.", vbInformation
        End If
    End If
End Sub

---------------------------------------------------
Some Notes:
you can use as SMTP server your ISP SMTP server ...
or u can use Hotmail SMTP Server :
mx05.hotmail.com
but when u use Hotmail SMTP ,  the (FromMail) and (ToMail) must be  hotmail e-mails..
I mean as example:
FromMail: Sender@hotmail.com
ToMail  : Receipent@hotmail.com
the two mails form Hotmail ...

That's All

Best Wishes

Wael-s


* if u get any problem contact me at:
sirgeo@hotvoice.com
you can do that with (Microsoft Winsock)
press (Ctrl+T ) and add (Microsoft Winsock)to your project..
then add winsock componnet on ur form ..(winsock1)
then put  7 textboxs, and name them as the following:

txtSMTP_Server
txtFromName
txtFromMail
txtToName
txtToMail
txtSubject
txtMsgBody
------------------------
in the delcare section of the form put this:

Private Enum SMTP_State
        MAIL_CONNECT
        MAIL_HELO
        MAIL_FROM
        MAIL_RCPTTO
        MAIL_DATA
        MAIL_DOT
        MAIL_QUIT
End Enum
Private m_State As SMTP_State
------------------------------------
Add command button (command1) and make its caption to: Send and this code in it:
 
 Winsock1.Close  ' This to close any exisiting connection
 Winsock1.Connect Trim$(txtSMTP_Server), 25  'Connect to the server
 m_State = MAIL_CONNECT 'Change the state of connection

----------------------------------------
Also you must add this in DataArrival of Winsock1:


Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim strServerResponse   As String
Dim strResponseCode     As String
Dim strDataToSend       As String
Dim m_strEncodedFiles As String
On Error Resume Next

    Winsock1.GetData strServerResponse
    strResponseCode = Left$(strServerResponse, 3)

    If strResponseCode = "250" Or _
       strResponseCode = "220" Or _
       strResponseCode = "354" Then
       
        Select Case m_State
            Case MAIL_CONNECT
                m_State = MAIL_HELO
                strDataToSend = Trim$(txtFromMail)
                strDataToSend = Left$(strDataToSend, _
                                InStr(1, strDataToSend, "@") - 1)

                Winsock1.SendData "HELO " & strDataToSend & vbCrLf

            Case MAIL_HELO
                m_State = MAIL_FROM
                Winsock1.SendData "MAIL FROM:" & Trim$(txtFromMail) & vbCrLf

            Case MAIL_FROM
                    m_State = MAIL_RCPTTO              
                    Winsock1.SendData "RCPT TO:" & Trim$(txtToMail) & vbCrLf

            Case MAIL_RCPTTO
                m_State = MAIL_DATA
                Winsock1.SendData "DATA" & vbCrLf
            Case MAIL_DATA
                m_State = MAIL_DOT
                '
                'So now we are sending a message body
                'Each line of text must be completed with
                'linefeed symbol (Chr$(10) or vbLf) not with vbCrLf
                '
                Winsock1.SendData "From:" & txtFromName & " <" & txtFromMail & ">" & vbCrLf

                Winsock1.SendData "To:" & txtToName & " <" & txtToMail & ">" & vbCrLf

                Winsock1.SendData "X-Mailer: VBMail Sender" & vbCrLf
                Winsock1.SendData "Mime-Version: 1.0" & vbCrLf
                Winsock1.SendData "Content-Type: text/" + "plain;" + vbTab + "charset=us-ascii" + vbCrLf

                Winsock1.SendData "Subject:" & txtSubject & vbLf & vbCrLf
                '
                '
                Dim varLines    As Variant
                Dim varLine     As Variant
                Dim strMessage  As String
               
                strMessage = txtMsgBody & vbCrLf & vbCrLf & m_strEncodedFiles

                m_strEncodedFiles = ""                 

                'Parse message to get lines (for VB6 only)
                varLines = Split(strMessage, vbCrLf)
                'clear memory
                strMessage = vbNullString
                '
                'Send each line of the message
                For Each varLine In varLines
                    Winsock1.SendData CStr(varLine) & vbLf
                Next
                '
                'Send a dot symbol to inform server
                'that sending of message comleted

                Winsock1.SendData vbCrLf & "." & vbCrLf

            Case MAIL_DOT
                m_State = MAIL_QUIT
                '
                'Send QUIT command to the server
                Winsock1.SendData "QUIT" & vbCrLf
                '
            Case MAIL_QUIT
                '
                'Close connection
                Winsock1.Close                

        End Select
       
    Else
        '
        'If we are here server replied with
        'unacceptable respose code therefore we need
        'close connection and inform user about problem
        '
        Winsock1.Close
        '
        If Not m_State = MAIL_QUIT Then
            MsgBox "SMTP Error: " & strServerResponse, _
                    vbInformation, "SMTP Error"
        Else
            MsgBox "Message sent successfuly.", vbInformation
        End If
    End If
End Sub

---------------------------------------------------
Some Notes:
you can use as SMTP server your ISP SMTP server ...
or u can use Hotmail SMTP Server :
mx05.hotmail.com
but when u use Hotmail SMTP ,  the (FromMail) and (ToMail) must be  hotmail e-mails..
I mean as example:
FromMail: Sender@hotmail.com
ToMail  : Receipent@hotmail.com
the two mails form Hotmail ...

That's All

Best Wishes

Wael-s


* if u get any problem contact me at:
sirgeo@hotvoice.com
hi,

check this exellent site : www.vbip.com

a must for the internet programming
There is a much easier way use email from VB if all you need to do is simply send an email and you do not need to manage incoming emails.  Most Windows PCs will already have a MAPI enabled email client configured and working.  We can access this from VB to send a message using the MAPI interface.  There is no need to roll your own SMTP server or create instances of Outlook if you use MAPI.  The beauty of using MAPI is that it does not rely on the PC having Outlook installed since any MAPI compliant mail system will work with this method.

To use the MAPI controls you must add the two MAPI controls to your project by adding the "Microsoft MAPI Controls 6.0" to your toolbar.  This uses MSMAPI32.OCX which you must distribute with your installer program.

The MAPI control consists of two parts, the 'MAPIMessages'and 'MAPISession' controls.  Add both of these controls to your form.  When you want to send an email, use the following code:

'-------------------------
   
    ' Log on to MAPI session
    If mpmMessage.SessionID = 0 Then
        mpsSession.SignOn
    End If

    mpmMessage.SessionID = mpsSession.SessionID

    ' Compose and send mail
    With mpmMessage
        .Compose
        .RecipDisplayName = tMsgRealName
        .RecipAddress = tMsgAddress
        .MsgSubject = tMsgSubj
        .MsgNoteText = tMsgBody
        .Send bConfirmSend
    End With
   
    mpsSession.SignOff
'----------------------------

where the variables used are as follows

tMsgRealName      - The real name of the recipient
tMsgAddress      - The email address of the recipient
tMsgBody      - the message body
tMsgSubj      - the email subject
bConfirmSend    - set to TRUE to Send the message inside a dialog box. Prompts the user for the various components of the message and submits the message to the mail server for delivery.   Set to FALSE (Default) to Submit the outgoing message to the mail server without displaying a dialog box. An error occurs if you attempt to send a message with no recipients or with missing attachment path names.

You can also attach files using this method, see the MSDN help for details.
Avatar of DanRollins
Hi alecam,
It appears that you have forgotten this question. I will ask Community Support to close it unless you finalize it within 7 days. I will ask a Community Support Moderator to:

    Accept vinnyd79's comment(s) as an answer.

alecam, if you think your question was not answered at all or if you need help, just post a new comment here; Community Support will help you.  DO NOT accept THIS comment as an answer.

EXPERTS: If you disagree with that recommendation, please post an explanatory comment.
==========
DanRollins -- EE database cleanup volunteer