วันเสาร์ที่ 20 ตุลาคม พ.ศ. 2555

Code VB สำหรับส่ง Mail ทาง Outlook

Code VB สำหรับส่ง e-mail และ Attach file ด้วย Outlook ที่คุณมี user อยู่ โดยตัวอย่าง จะส่ง e-mail และ file Test.xlsx ไปยัง To และ Cc.  x.automation2012@gmail.com ซึ่งกำหนดไว้ 2 เงื่อนไข คือ
- Show หน้าต่างของ e-mail เพื่อให้กดปุ่ม Send : ให้เลือก .Display
- ส่ง e-mail ทันที: ให้เลือก .Send

ซึ่งเนื่องจากเราจะส่ง e-mail ผ่านทาง Outlook ดังนั้นเราจึงต้องเพิ่ม Microsoft Outlook Component ให้กับ VB Project ก่อนที่จะ Coding โดยให้เพิ่ม "Microsoft Outlook 12.0 Object Library" ดังรูป



ตัวอย่างของโปรแกรม โดยเลือกส่ง e-mail ทันที
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim oapp As Outlook.Application
    Dim oEmail As Outlook.MailItem
   
    Set oapp = New Outlook.Application
    Set oEmail = oapp.CreateItem(olMailItem)
 
    On Error GoTo SendEmailErr
    With oEmail
       .To = "x.automation2012@gmail.com"
       .CC = "x.automation2012@gmail.com"
       .Subject = "Energy Planing"
       .BodyFormat = olFormatPlain
       .Body = "Test"
       '.Importance = olImportanceHigh
       .ReadReceiptRequested = True
       .Attachments.Add "D:\Test.xlsx", olByValue
       .Recipients.ResolveAll
       .Save
       '.Display 'Show the email message and allow for editing before sending
       .Send 'You can automatically send the email without displaying it.
    End With
    Set oEmail = Nothing
    'oapp.Quit
    Set oapp = Nothing
   
Exit_SendEmail:
    Set oEmail = Nothing
    Set oapp = Nothing
    Exit Sub
   
SendEmailErr:
    MsgBox "Error " & Err.description
    Resume Exit_SendEmail
End Sub

ไม่มีความคิดเห็น:

แสดงความคิดเห็น