How to send a mail using smtp in office365 in .NET with attachment

Hi,

how to send a mail using smtp in office365 in .NET with attachment

Public Function SendMail(ByVal ToAddress As String, ByVal Subject As String, ByVal Body As String, Optional ByVal AttachmentPath As String = "", Optional ByVal CCAddress As String = "") As String
        Dim MailMsg As New MailMessage
        Dim mfrom = New MailAddress("FromEmailAddress")
        MailMsg.From = mfrom
        MailMsg.To.Add(ToAddress)
        If Not String.IsNullOrEmpty(CCAddress) Then
            MailMsg.CC.Add(CCAddress)
        End If
        MailMsg.Subject = Subject
        MailMsg.IsBodyHtml = True
        MailMsg.Body = Body

        If Len(Trim(AttachmentPath & "")) <> 0 Then
            'Putting all documents path to list
            Dim lstAttachmentPaths As New List(Of String)
            For Each s As String In AttachmentPath.Split("|"c)
                lstAttachmentPaths.Add(s)
            Next

            'Loop through path list to mail
            Dim intListLoop As Integer
            For intListLoop = 0 To lstAttachmentPaths.Count - 1
                Dim attachFile As New Attachment(lstAttachmentPaths(intListLoop))
                MailMsg.Attachments.Add(attachFile)
            Next intListLoop
        End If
   
        Dim mailClient As New SmtpClient()
        mailClient.Host = "smtp.office365.com"
        mailClient.Credentials = New System.Net.NetworkCredential("FromEmailAddress", "pwd")
        mailClient.Port = 587
        mailClient.EnableSsl = True
        MailMsg.Priority = MailPriority.High
        mailClient.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.Network
        Try
            mailClient.Send(MailMsg)
            MailMsg.Dispose() 'Solution - The process cannot access the file [filename] because it is being used by another process.
            Return Nothing
        Catch ex As Exception
            Return ex.ToString
        End Try
     
    End Function

Comments