0

I have the following code to connect to ExchangeOnline >> generate csv file >> send the file by email using Office 365 smtp:-

Connect-ExchangeOnline
$SiteIDs = '64898c8f-2d5f-4e0e-9a9b-eb9828975a9e','20e6140c-0441-4988-b36c-c61cf3400847'
$Operations = @('FileAccessed','FileDownloaded','FileDeleted')
$OutputFile = ".\UnifiedAuditLog_FULL.csv"
$Today = Get-Date -Date (Get-Date -Format “yyyy-MM-dd”)
$intDays = 14
For ($i=0; $i -le $intDays; $i++){
  For ($j=23; $j -ge 0; $j--){
    $StartDate = ($Today.AddDays(-$i)).AddHours($j)
    $EndDate = ($Today.AddDays(-$i)).AddHours($j + 1)
    $Audit = Search-UnifiedAuditLog -StartDate $StartDate -EndDate $EndDate -ResultSize 5000 -SiteIds $SiteIDs -RecordType SharePointFileOperation -Operations $Operations 
    $ConvertAudit = $Audit | Select-Object -ExpandProperty AuditData | ConvertFrom-Json
    $OutputFile0 = ".\UnifiedAuditLog_FULL"+$i+$j+"ALL0.csv"
    $ConvertAudit | Select-Object CreationTime,UserId,Operation,Workload,ObjectID,SiteUrl,SourceFileName,ClientIP,UserAgent | Export-Csv $OutputFile0 -NoTypeInformation -Force -Append
    Write-Host $StartDate `t $Audit.Count
    # File to be attached in email
$attachment = new-object Net.Mail.Attachment("D:\"+$OutputFile0)

# Configure SMTP server
$smtpServer = "smtp.office365.com"
$mailMessage = new-object Net.Mail.MailMessage
$smtpObj = new-object Net.Mail.SmtpClient($smtpServer)

# Set email parameters
$mailMessage.From = "***"
$mailMessage.ReplyTo = "****"
$mailMessage.To.Add("****")
$mailMessage.subject = "[MAIL SUBJECT]"
$mailMessage.body = "[MAIL BODY]"
$mailMessage.Attachments.Add($attachment)

# Send email
$smtpObj.Send($mailMessage)
$attachment.Dispose()
  
  
  
  
  
  }
}
Disconnect-ExchangeOnline

But i will get this exception:-

Exception calling "Send" with "1" argument(s): "Service not available, closing transmission channel. The server
response was: Cannot connect to SMTP server 40.101.76.178 (40.101.76.178:25), connect error 10060"
At line:28 char:1
+ $smtpObj.Send($mailMessage)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SmtpException

Any advice?

enter image description here

Update-1

Now when i define the port number as follow:-

$smtpObj = new-object Net.Mail.SmtpClient($smtpServer,587)

I will get this error instead:-

Exception calling "Send" with "1" argument(s): "Error in processing. The server response was: 5.7.3 STARTTLS is
required to send mail [VI1P194CA0025.EURP194.PROD.OUTLOOK.COM]"
At line:28 char:1
+ $smtpObj.Send($mailMessage)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SmtpException

Edit I also tried this:-

Read-Host -Prompt "Enter your tenant password" -AsSecureString | ConvertFrom-SecureString | Out-File "O365.key"

Connect-ExchangeOnline
$SiteIDs = '64898c8f-2d5f-4e0e-9a9b-eb9828975a9e','20e6140c-0441-4988-b36c-c61cf3400847'
$Operations = @('FileAccessed','FileDownloaded','FileDeleted')
$OutputFile = ".\UnifiedAuditLog_FULL.csv"
$Today = Get-Date -Date (Get-Date -Format “yyyy-MM-dd”)
$intDays = 2
$TenantPass = cat "O365.key" | ConvertTo-SecureString
$emailCredential = New-Object System.Net.NetworkCredential("test.user@***.com", $TenantPass)
For ($i=0; $i -le $intDays; $i++){
  For ($j=23; $j -ge 0; $j--){
    $StartDate = ($Today.AddDays(-$i)).AddHours($j)
    $EndDate = ($Today.AddDays(-$i)).AddHours($j + 1)
    $Audit = Search-UnifiedAuditLog -StartDate $StartDate -EndDate $EndDate -ResultSize 5000 -SiteIds $SiteIDs -RecordType SharePointFileOperation -Operations $Operations 
    $ConvertAudit = $Audit | Select-Object -ExpandProperty AuditData | ConvertFrom-Json
    $OutputFile0 = ".\UnifiedAuditLog_FULL"+$i+$j+"ALL0.csv"
    $ConvertAudit | Select-Object CreationTime,UserId,Operation,Workload,ObjectID,SiteUrl,SourceFileName,ClientIP,UserAgent | Export-Csv $OutputFile0 -NoTypeInformation -Force -Append
    Write-Host $StartDate `t $Audit.Count
    
    # File to be attached in email
$attachment = new-object Net.Mail.Attachment("D:\"+$OutputFile0)

# Configure SMTP server
$smtpServer = "smtp.office365.com"
$mailMessage = new-object Net.Mail.MailMessage
$smtpObj = new-object Net.Mail.SmtpClient($smtpServer,587)
$smtpObj.EnableSSl = $true
$smtpObj.Credentials = $emailCredential
# Set email parameters
$mailMessage.From = "test.user@***.com"
$mailMessage.To.add("test.user@***.com")
$mailMessage.subject = "[MAIL SUBJECT]"
#$mailMessage.body = "[MAIL BODY]"
#$mailMessage.Attachments.Add($attachment)

# Send email
$smtpObj.Send($mailMessage)
$attachment.Dispose()
  
  
  
  
  
  }
}
Disconnect-ExchangeOnline

but i got this error:-

Exception calling "Send" with "1" argument(s): "The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.7.57 Client not authenticated to send mail. Error: 535 5.7.139
Authentication unsuccessful, the request did not meet the criteria to be authenticated successfully. Contact your
administrator. [VI1P191CA0005.EURP191.PROD.OUTLOOK.COM]"
At line:26 char:1
+ $smtpObj.Send($mailMessage)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SmtpException

Although the user i am using has SmtpClientAuthenticationDisabled = False, as follow

PS D:\> Get-CASMailbox -Identity test.user@***.com
Name          ActiveSyncEnabled OWAEnabled PopEnabled ImapEnabled MapiEnabled SmtpClientAuthenticationDisabled
----          ----------------- ---------- ---------- ----------- ----------- --------------------------------
test.user@***.com True              True       True       True        True        False
John John
  • 1
  • 72
  • 238
  • 501
  • 1
    Try commenting out the body and the attachment and see if it works. Also add default credentials as shown in following posting : https://stackoverflow.com/questions/2766928/how-to-set-username-and-password-for-smtpclient-object-in-net?force_isolation=true – jdweng Dec 15 '22 at 09:58
  • @jdweng i tried commenting out the body and the attachment >> and i define the credental as mentioned on the link you provided, but i got this error `Exception calling "Send" with "1" argument(s): "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 Client not authenticated to send mail. Error: 535 5.7.139 – John John Dec 15 '22 at 10:05
  • ... Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [VI1PR0802CA0031.eurprd08.prod.outlook.com]" At line:28 char:1+ smtpObj.Send($mailMessage)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SmtpException` – John John Dec 15 '22 at 10:06
  • @johnGu Follow the instructions under where it says ["Enable SMTP AUTH for specific mailboxes"](https://learn.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission#enable-smtp-auth-for-specific-mailboxes) – Mathias R. Jessen Dec 15 '22 at 10:19
  • The FROM address and the credentials have to be from same account – jdweng Dec 15 '22 at 10:27
  • @jdweng they are already .. but things are not working – John John Dec 15 '22 at 10:28
  • The fixes now are allowing connection to complete, but you are failing when sending the email. Are you failing first time through loops or after more than one email gets sent? – jdweng Dec 15 '22 at 10:32
  • @jdweng fail on the first attempt – John John Dec 15 '22 at 10:35
  • @jdweng can you check my edit please? – John John Dec 15 '22 at 10:41
  • Are you inside a corporate network? Is server a company server or you own account? If you are inside a company firewall all smtp ports are forwarded to the company email proxy server where credentials are checked. So you cannot get to an outside email server. The error you are getting could be the Forwarding is sending the email to different server. – jdweng Dec 15 '22 at 10:51
  • @jdweng i am in my home >> and i am trying to connect to Office 365 SMTP – John John Dec 15 '22 at 10:52
  • Are you connecting to your personal account or into your company account? You may be having issues getting into your company account. Your personnel credentials may be used instead of the company credentials. Try for credentials : smtpClient.UseDefaultCredentials = true; See : https://stackoverflow.com/questions/29648391/exception-using-default-smtp-credentials-on-office365-client-was-not-authentic?force_isolation=true – jdweng Dec 15 '22 at 11:16
  • @jdweng using my compay account of course – John John Dec 15 '22 at 12:02
  • You need to be inside the firewall. if inside firewall you may be able to use port 25 instead of 587. It all depends on how your company has setup the smtp. If company is using a relay you may not even need credentials. Relay is used for devices like printers. See : https://learn.microsoft.com/en-us/exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-microsoft-365-or-office-365?force_isolation=true – jdweng Dec 15 '22 at 12:41
  • @jdweng i do not have any firewall.. i am connected from home – John John Dec 15 '22 at 13:06
  • The firewall is at the company. You are at home but the email server is inside a firewall at company. – jdweng Dec 15 '22 at 13:15
  • @jdweng i am connected to the Office 365 smtp not to our company smtp – John John Dec 15 '22 at 13:56

0 Answers0