VBA‎ > ‎

Send an email from Access database using gmail


'This first set of code just captures all the relevant information to send the email from a form in your Access database.
        Dim strMailto As String
        strMailto = Me.ToEmailAddress
        Dim strMailFrom As String
        strMailFrom = Me.MailFromAddress
        Dim strSubject As String
        strSubject = Me.Subject
        Dim StrBody As String
        StrBody = Me.Body
        Dim strCC As String
        If IsNull(Me.emailcc) = False Then
            strCC = Me.emailcc
        End If
        Dim strBCC As String
        If IsNull(Me.emailbcc) = False Then
            strBCC = Me.emailbcc
        End If

'Now begins the code to actually send the email

        Dim msg As Object
        Set msg = CreateObject("CDO.Message")
        msg.FROM = strMailFrom
        msg.To = strMailto
        msg.Subject = strSubject
        msg.TextBody = StrBody
        msg.Cc = strCC
        msg.bcc = strBCC
        msg.replyto = strMailFrom

'Optionally, our Access form allowed the user to attached 3 files to the email        
        If IsNull(Me.attachment) = False Then
             Dim strAttachment As String
             strAttachment = Me.attachment
             msg.addattachment "file://" & strAttachment & ""
        End If
        If IsNull(Me.Attachment2) = False Then
             Dim strAttachment2 As String
             strAttachment2 = Me.Attachment2
             msg.addattachment "file://" & strAttachment2 & ""
        End If
        If IsNull(Me.Attachment3) = False Then
             Dim strAttachment3 As String
             strAttachment3 = Me.Attachment3
             msg.addattachment "file://" & strAttachment3 & ""
        End If

'Now send it
         msg.configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
        msg.configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
        msg.configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        msg.configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "yourname@gmail.com"
        msg.configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "yourgmailpassword"
        msg.configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
        msg.configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1