├── .DS_Store
├── .editorconfig
├── .gitattributes
├── .github
├── .DS_Store
└── workflows
│ └── ci.yml
├── .gitignore
├── Build.ps1
├── Directory.Build.props
├── Directory.Version.props
├── LICENSE
├── README.md
├── assets
└── Serilog.snk
├── global.json
├── serilog-sink-nuget.png
├── serilog-sinks-email.sln
├── src
└── Serilog.Sinks.Email
│ ├── LoggerConfigurationEmailExtensions.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── Serilog.Sinks.Email.csproj
│ └── Sinks
│ └── Email
│ ├── EmailMessage.cs
│ ├── EmailSink.cs
│ ├── EmailSinkOptions.cs
│ ├── IBatchTextFormatter.cs
│ ├── IEmailTransport.cs
│ └── MailKitEmailTransport.cs
└── test
├── Serilog.Sinks.Email.Tests
├── EmailSinkTests.cs
├── LoggerConfigurationEmailExtensionsTests.cs
├── Serilog.Sinks.Email.Tests.csproj
└── Support
│ ├── HtmlTableFormatter.cs
│ ├── TestEmailTransport.cs
│ └── UseCultureAttribute.cs
└── TestHarness
├── Program.cs
└── TestHarness.csproj
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/serilog/serilog-sinks-email/2bcf54cbacd00912350ae67f0f987bf47cbaf35b/.DS_Store
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | trim_trailing_whitespace = true
5 | insert_final_newline = true
6 | indent_style = space
7 | indent_size = 4
8 |
9 | [*.{csproj,json,config,yml,props}]
10 | indent_size = 2
11 |
12 | [*.sh]
13 | end_of_line = lf
14 |
15 | [*.{cmd, bat}]
16 | end_of_line = crlf
17 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 |
3 | * text=auto
4 |
--------------------------------------------------------------------------------
/.github/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/serilog/serilog-sinks-email/2bcf54cbacd00912350ae67f0f987bf47cbaf35b/.github/.DS_Store
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | # If this file is renamed, the incrementing run attempt number will be reset.
2 |
3 | name: CI
4 |
5 | on:
6 | push:
7 | branches: [ "dev", "main" ]
8 | pull_request:
9 | branches: [ "dev", "main" ]
10 |
11 | env:
12 | CI_BUILD_NUMBER_BASE: ${{ github.run_number }}
13 | CI_TARGET_BRANCH: ${{ github.head_ref || github.ref_name }}
14 |
15 | jobs:
16 | build:
17 |
18 | # The build must run on Windows so that .NET Framework targets can be built and tested.
19 | runs-on: windows-latest
20 |
21 | permissions:
22 | contents: write
23 |
24 | steps:
25 | - uses: actions/checkout@v4
26 | - name: Setup
27 | uses: actions/setup-dotnet@v4
28 | with:
29 | dotnet-version: 9.0.x
30 | - name: Compute build number
31 | shell: bash
32 | run: |
33 | echo "CI_BUILD_NUMBER=$(($CI_BUILD_NUMBER_BASE+2300))" >> $GITHUB_ENV
34 | - name: Build and Publish
35 | env:
36 | DOTNET_CLI_TELEMETRY_OPTOUT: true
37 | NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
38 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
39 | shell: pwsh
40 | run: |
41 | ./Build.ps1
42 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.sln.docstates
8 | project.lock.json
9 |
10 | # Build results
11 | [Dd]ebug/
12 | [Dd]ebugPublic/
13 | [Rr]elease/
14 | [Rr]eleases/
15 | x64/
16 | x86/
17 | build/
18 | bld/
19 | [Bb]in/
20 | [Oo]bj/
21 |
22 | # Roslyn cache directories
23 | *.ide/
24 |
25 | # MSTest test Results
26 | [Tt]est[Rr]esult*/
27 | [Bb]uild[Ll]og.*
28 |
29 | #NUNIT
30 | *.VisualState.xml
31 | TestResult.xml
32 |
33 | # Build Results of an ATL Project
34 | [Dd]ebugPS/
35 | [Rr]eleasePS/
36 | dlldata.c
37 |
38 | *_i.c
39 | *_p.c
40 | *_i.h
41 | *.ilk
42 | *.meta
43 | *.obj
44 | *.pch
45 | *.pdb
46 | *.pgc
47 | *.pgd
48 | *.rsp
49 | *.sbr
50 | *.tlb
51 | *.tli
52 | *.tlh
53 | *.tmp
54 | *.tmp_proj
55 | *.log
56 | *.vspscc
57 | *.vssscc
58 | .builds
59 | *.pidb
60 | *.svclog
61 | *.scc
62 |
63 | # Chutzpah Test files
64 | _Chutzpah*
65 |
66 | # Visual C++ cache files
67 | ipch/
68 | *.aps
69 | *.ncb
70 | *.opensdf
71 | *.sdf
72 | *.cachefile
73 |
74 | # Visual Studio profiler
75 | *.psess
76 | *.vsp
77 | *.vspx
78 |
79 | # TFS 2012 Local Workspace
80 | $tf/
81 |
82 | # Guidance Automation Toolkit
83 | *.gpState
84 |
85 | # ReSharper is a .NET coding add-in
86 | _ReSharper*/
87 | *.[Rr]e[Ss]harper
88 | *.DotSettings.user
89 |
90 | # JustCode is a .NET coding addin-in
91 | .JustCode
92 |
93 | # TeamCity is a build add-in
94 | _TeamCity*
95 |
96 | # DotCover is a Code Coverage Tool
97 | *.dotCover
98 |
99 | # NCrunch
100 | _NCrunch_*
101 | .*crunch*.local.xml
102 |
103 | # MightyMoose
104 | *.mm.*
105 | AutoTest.Net/
106 |
107 | # Web workbench (sass)
108 | .sass-cache/
109 |
110 | # Installshield output folder
111 | [Ee]xpress/
112 |
113 | # DocProject is a documentation generator add-in
114 | DocProject/buildhelp/
115 | DocProject/Help/*.HxT
116 | DocProject/Help/*.HxC
117 | DocProject/Help/*.hhc
118 | DocProject/Help/*.hhk
119 | DocProject/Help/*.hhp
120 | DocProject/Help/Html2
121 | DocProject/Help/html
122 |
123 | # Click-Once directory
124 | publish/
125 |
126 | # Publish Web Output
127 | *.[Pp]ublish.xml
128 | *.azurePubxml
129 | # TODO: Comment the next line if you want to checkin your web deploy settings
130 | # but database connection strings (with potential passwords) will be unencrypted
131 | *.pubxml
132 | *.publishproj
133 |
134 | # NuGet Packages
135 | *.nupkg
136 | # The packages folder can be ignored because of Package Restore
137 | **/packages/*
138 | # except build/, which is used as an MSBuild target.
139 | !**/packages/build/
140 | # If using the old MSBuild-Integrated Package Restore, uncomment this:
141 | #!**/packages/repositories.config
142 |
143 | # Windows Azure Build Output
144 | csx/
145 | *.build.csdef
146 |
147 | # Windows Store app package directory
148 | AppPackages/
149 |
150 | # Others
151 | sql/
152 | *.Cache
153 | ClientBin/
154 | [Ss]tyle[Cc]op.*
155 | ~$*
156 | *~
157 | *.dbmdl
158 | *.dbproj.schemaview
159 | *.pfx
160 | *.publishsettings
161 | node_modules/
162 |
163 | # RIA/Silverlight projects
164 | Generated_Code/
165 |
166 | # Backup & report files from converting an old project file
167 | # to a newer Visual Studio version. Backup files are not needed,
168 | # because we have git ;-)
169 | _UpgradeReport_Files/
170 | Backup*/
171 | UpgradeLog*.XML
172 | UpgradeLog*.htm
173 |
174 | # SQL Server files
175 | *.mdf
176 | *.ldf
177 |
178 | # Business Intelligence projects
179 | *.rdl.data
180 | *.bim.layout
181 | *.bim_*.settings
182 |
183 | # Microsoft Fakes
184 | FakesAssemblies/
185 | /.vs
186 |
187 | .idea/
188 |
--------------------------------------------------------------------------------
/Build.ps1:
--------------------------------------------------------------------------------
1 | Write-Output "build: Tool versions follow"
2 |
3 | dotnet --version
4 | dotnet --list-sdks
5 |
6 | Write-Output "build: Build started"
7 |
8 | Push-Location $PSScriptRoot
9 | try {
10 | if(Test-Path .\artifacts) {
11 | Write-Output "build: Cleaning ./artifacts"
12 | Remove-Item ./artifacts -Force -Recurse
13 | }
14 |
15 | & dotnet restore --no-cache
16 |
17 | $dbp = [Xml] (Get-Content .\Directory.Version.props)
18 | $versionPrefix = $dbp.Project.PropertyGroup.VersionPrefix
19 |
20 | Write-Output "build: Package version prefix is $versionPrefix"
21 |
22 | $branch = @{ $true = $env:CI_TARGET_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$NULL -ne $env:CI_TARGET_BRANCH];
23 | $revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:CI_BUILD_NUMBER, 10); $false = "local" }[$NULL -ne $env:CI_BUILD_NUMBER];
24 | $suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)) -replace '([^a-zA-Z0-9\-]*)', '')-$revision"}[$branch -eq "main" -and $revision -ne "local"]
25 | $commitHash = $(git rev-parse --short HEAD)
26 | $buildSuffix = @{ $true = "$($suffix)-$($commitHash)"; $false = "$($branch)-$($commitHash)" }[$suffix -ne ""]
27 |
28 | Write-Output "build: Package version suffix is $suffix"
29 | Write-Output "build: Build version suffix is $buildSuffix"
30 |
31 | & dotnet build -c Release --version-suffix=$buildSuffix /p:ContinuousIntegrationBuild=true
32 | if($LASTEXITCODE -ne 0) { throw "Build failed" }
33 |
34 | foreach ($src in Get-ChildItem src/*) {
35 | Push-Location $src
36 |
37 | Write-Output "build: Packaging project in $src"
38 |
39 | if ($suffix) {
40 | & dotnet pack -c Release --no-build --no-restore -o ../../artifacts --version-suffix=$suffix
41 | } else {
42 | & dotnet pack -c Release --no-build --no-restore -o ../../artifacts
43 | }
44 | if($LASTEXITCODE -ne 0) { throw "Packaging failed" }
45 |
46 | Pop-Location
47 | }
48 |
49 | foreach ($test in Get-ChildItem test/*.Tests) {
50 | Push-Location $test
51 |
52 | Write-Output "build: Testing project in $test"
53 |
54 | & dotnet test -c Release --no-build --no-restore
55 | if($LASTEXITCODE -ne 0) { throw "Testing failed" }
56 |
57 | Pop-Location
58 | }
59 |
60 | if ($env:NUGET_API_KEY) {
61 | # GitHub Actions will only supply this to branch builds and not PRs. We publish
62 | # builds from any branch this action targets (i.e. main and dev).
63 |
64 | Write-Output "build: Publishing NuGet packages"
65 |
66 | foreach ($nupkg in Get-ChildItem artifacts/*.nupkg) {
67 | & dotnet nuget push -k $env:NUGET_API_KEY -s https://api.nuget.org/v3/index.json "$nupkg"
68 | if($LASTEXITCODE -ne 0) { throw "Publishing failed" }
69 | }
70 |
71 | if (!($suffix)) {
72 | Write-Output "build: Creating release for version $versionPrefix"
73 |
74 | iex "gh release create v$versionPrefix --title v$versionPrefix --generate-notes $(get-item ./artifacts/*.nupkg) $(get-item ./artifacts/*.snupkg)"
75 | }
76 | }
77 | } finally {
78 | Pop-Location
79 | }
80 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 | latest
7 | True
8 |
9 | true
10 | $(MSBuildThisFileDirectory)assets/Serilog.snk
11 | false
12 | enable
13 | enable
14 | true
15 | true
16 | true
17 | true
18 | snupkg
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/Directory.Version.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.1.1
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Serilog.Sinks.Email [](https://github.com/serilog/serilog-sinks-email/actions) [](https://www.nuget.org/packages/Serilog.Sinks.Email/)
2 |
3 | Sends log events by SMTP email.
4 |
5 | > ℹ️ Version 3.x of this package changes the name and structure of many configuration parameters from their 2.x names; see below for detailed information.
6 |
7 | **Package Id:** [Serilog.Sinks.Email](http://nuget.org/packages/serilog.sinks.email)
8 |
9 | ```csharp
10 | await using var log = new LoggerConfiguration()
11 | .WriteTo.Email(
12 | from: "app@example.com",
13 | to: "support@example.com",
14 | host: "smtp.example.com")
15 | .CreateLogger();
16 | ```
17 |
18 | Supported options are:
19 |
20 | | Parameter | Description |
21 | |------------------------|-------------------------------------------------------------------------------------------------------------------------------------|
22 | | `from` | The email address emails will be sent from. |
23 | | `to` | The email address emails will be sent to. Multiple addresses can be separated with commas or semicolons. |
24 | | `host` | The SMTP server to use. |
25 | | `port` | The port used for the SMTP connection. The default is 25. |
26 | | `connectionSecurity` | Choose the security applied to the SMTP connection. This enumeration type is supplied by MailKit. The default is `Auto`. |
27 | | `credentials` | The network credentials to use to authenticate with the mail server. |
28 | | `subject` | A message template describing the email subject. The default is `"Log Messages"`. |
29 | | `body` | A message template describing the format of the email body. The default is `"{Timestamp} [{Level}] {Message}{NewLine}{Exception}"`. |
30 | | `formatProvider` | Supplies culture-specific formatting information. The default is to use the current culture. |
31 |
32 | An overload accepting `EmailSinkOptions` can be used to specify advanced options such as batched and/or HTML body templates.
33 |
34 | ## Sending batch email
35 |
36 | To send batch email, supply `WriteTo.Email` with a batch size:
37 |
38 | ```csharp
39 | await using var log = new LoggerConfiguration()
40 | .WriteTo.Email(
41 | options: new()
42 | {
43 | From = "app@example.com",
44 | To = "support@example.com",
45 | Host = "smtp.example.com",
46 | },
47 | batchingOptions: new()
48 | {
49 | BatchSizeLimit = 10,
50 | BufferingTimeLimit = TimeSpan.FromSeconds(30),
51 | })
52 | .CreateLogger();
53 | ```
54 |
55 | Batch formatting can be customized using `options.Body`.
56 |
57 | ## Sending HTML email
58 |
59 | To send HTML email, specify a custom `IBatchTextFormatter` in `options.Body` and set `options.IsBodyHtml` to `true`:
60 |
61 |
62 | ```csharp
63 | await using var log = new LoggerConfiguration()
64 | .WriteTo.Email(
65 | options: new()
66 | {
67 | From = "app@example.com",
68 | To = "support@example.com",
69 | Host = "smtp.example.com",
70 | Body = new MyHtmlBodyFormatter(),
71 | IsBodyHtml = true,
72 | },
73 | batchingOptions: new()
74 | {
75 | BatchSizeLimit = 10,
76 | BufferingTimeLimit = TimeSpan.FromSeconds(30),
77 | })
78 | .CreateLogger();
79 | ```
80 |
81 | A simplistic HTML formatter is shown below:
82 |
83 | ```csharp
84 | class MyHtmlBodyFormatter : IBatchTextFormatter
85 | {
86 | public void FormatBatch(IEnumerable logEvents, TextWriter output)
87 | {
88 | output.Write("");
89 | foreach (var logEvent in logEvents)
90 | {
91 | output.Write("");
92 | Format(logEvent, output);
93 | output.Write("
");
94 | }
95 |
96 | output.Write("
");
97 | }
98 |
99 | public void Format(LogEvent logEvent, TextWriter output)
100 | {
101 | using var buffer = new StringWriter();
102 | logEvent.RenderMessage(buffer);
103 | output.Write(WebUtility.HtmlEncode(buffer.ToString()));
104 | }
105 | }
106 | ```
107 |
--------------------------------------------------------------------------------
/assets/Serilog.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/serilog/serilog-sinks-email/2bcf54cbacd00912350ae67f0f987bf47cbaf35b/assets/Serilog.snk
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "9.0.200",
4 | "allowPrerelease": false,
5 | "rollForward": "latestFeature"
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/serilog-sink-nuget.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/serilog/serilog-sinks-email/2bcf54cbacd00912350ae67f0f987bf47cbaf35b/serilog-sink-nuget.png
--------------------------------------------------------------------------------
/serilog-sinks-email.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30011.22
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "assets", "assets", "{DACEA959-EA30-47CA-A300-6756E3EB35A4}"
7 | ProjectSection(SolutionItems) = preProject
8 | .editorconfig = .editorconfig
9 | .gitignore = .gitignore
10 | README.md = README.md
11 | assets\Serilog.snk = assets\Serilog.snk
12 | Build.ps1 = Build.ps1
13 | Directory.Build.props = Directory.Build.props
14 | Directory.Version.props = Directory.Version.props
15 | global.json = global.json
16 | EndProjectSection
17 | EndProject
18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{340DBC35-BD09-414B-818C-978FBCA4CDF1}"
19 | EndProject
20 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{70D17E86-9325-4228-8512-547B3E0774A1}"
21 | EndProject
22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.Sinks.Email.Tests", "test\Serilog.Sinks.Email.Tests\Serilog.Sinks.Email.Tests.csproj", "{7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}"
23 | EndProject
24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.Sinks.Email", "src\Serilog.Sinks.Email\Serilog.Sinks.Email.csproj", "{96A53337-1692-4884-BE03-34A97147EACE}"
25 | EndProject
26 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestHarness", "test\TestHarness\TestHarness.csproj", "{31356ADE-0243-4286-9187-C4A398BD4887}"
27 | EndProject
28 | Global
29 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
30 | Debug|Any CPU = Debug|Any CPU
31 | Debug|x64 = Debug|x64
32 | Debug|x86 = Debug|x86
33 | Release|Any CPU = Release|Any CPU
34 | Release|x64 = Release|x64
35 | Release|x86 = Release|x86
36 | EndGlobalSection
37 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
38 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
39 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Debug|Any CPU.Build.0 = Debug|Any CPU
40 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Debug|x64.ActiveCfg = Debug|Any CPU
41 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Debug|x64.Build.0 = Debug|Any CPU
42 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Debug|x86.ActiveCfg = Debug|Any CPU
43 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Debug|x86.Build.0 = Debug|Any CPU
44 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Release|Any CPU.ActiveCfg = Release|Any CPU
45 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Release|Any CPU.Build.0 = Release|Any CPU
46 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Release|x64.ActiveCfg = Release|Any CPU
47 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Release|x64.Build.0 = Release|Any CPU
48 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Release|x86.ActiveCfg = Release|Any CPU
49 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97}.Release|x86.Build.0 = Release|Any CPU
50 | {96A53337-1692-4884-BE03-34A97147EACE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
51 | {96A53337-1692-4884-BE03-34A97147EACE}.Debug|Any CPU.Build.0 = Debug|Any CPU
52 | {96A53337-1692-4884-BE03-34A97147EACE}.Debug|x64.ActiveCfg = Debug|Any CPU
53 | {96A53337-1692-4884-BE03-34A97147EACE}.Debug|x64.Build.0 = Debug|Any CPU
54 | {96A53337-1692-4884-BE03-34A97147EACE}.Debug|x86.ActiveCfg = Debug|Any CPU
55 | {96A53337-1692-4884-BE03-34A97147EACE}.Debug|x86.Build.0 = Debug|Any CPU
56 | {96A53337-1692-4884-BE03-34A97147EACE}.Release|Any CPU.ActiveCfg = Release|Any CPU
57 | {96A53337-1692-4884-BE03-34A97147EACE}.Release|Any CPU.Build.0 = Release|Any CPU
58 | {96A53337-1692-4884-BE03-34A97147EACE}.Release|x64.ActiveCfg = Release|Any CPU
59 | {96A53337-1692-4884-BE03-34A97147EACE}.Release|x64.Build.0 = Release|Any CPU
60 | {96A53337-1692-4884-BE03-34A97147EACE}.Release|x86.ActiveCfg = Release|Any CPU
61 | {96A53337-1692-4884-BE03-34A97147EACE}.Release|x86.Build.0 = Release|Any CPU
62 | {31356ADE-0243-4286-9187-C4A398BD4887}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
63 | {31356ADE-0243-4286-9187-C4A398BD4887}.Debug|Any CPU.Build.0 = Debug|Any CPU
64 | {31356ADE-0243-4286-9187-C4A398BD4887}.Debug|x64.ActiveCfg = Debug|Any CPU
65 | {31356ADE-0243-4286-9187-C4A398BD4887}.Debug|x64.Build.0 = Debug|Any CPU
66 | {31356ADE-0243-4286-9187-C4A398BD4887}.Debug|x86.ActiveCfg = Debug|Any CPU
67 | {31356ADE-0243-4286-9187-C4A398BD4887}.Debug|x86.Build.0 = Debug|Any CPU
68 | {31356ADE-0243-4286-9187-C4A398BD4887}.Release|Any CPU.ActiveCfg = Release|Any CPU
69 | {31356ADE-0243-4286-9187-C4A398BD4887}.Release|Any CPU.Build.0 = Release|Any CPU
70 | {31356ADE-0243-4286-9187-C4A398BD4887}.Release|x64.ActiveCfg = Release|Any CPU
71 | {31356ADE-0243-4286-9187-C4A398BD4887}.Release|x64.Build.0 = Release|Any CPU
72 | {31356ADE-0243-4286-9187-C4A398BD4887}.Release|x86.ActiveCfg = Release|Any CPU
73 | {31356ADE-0243-4286-9187-C4A398BD4887}.Release|x86.Build.0 = Release|Any CPU
74 | EndGlobalSection
75 | GlobalSection(SolutionProperties) = preSolution
76 | HideSolutionNode = FALSE
77 | EndGlobalSection
78 | GlobalSection(NestedProjects) = preSolution
79 | {7BC4F72D-F40B-4F7C-8EBD-E50F0D6C0D97} = {70D17E86-9325-4228-8512-547B3E0774A1}
80 | {96A53337-1692-4884-BE03-34A97147EACE} = {340DBC35-BD09-414B-818C-978FBCA4CDF1}
81 | {31356ADE-0243-4286-9187-C4A398BD4887} = {70D17E86-9325-4228-8512-547B3E0774A1}
82 | EndGlobalSection
83 | GlobalSection(ExtensibilityGlobals) = postSolution
84 | SolutionGuid = {9E7E183E-7DDE-45DB-ACE9-2055FB3B7847}
85 | EndGlobalSection
86 | EndGlobal
87 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.Email/LoggerConfigurationEmailExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright © Serilog Contributors
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | // http://www.apache.org/licenses/LICENSE-2.0
7 | //
8 | // Unless required by applicable law or agreed to in writing, software
9 | // distributed under the License is distributed on an "AS IS" BASIS,
10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | // See the License for the specific language governing permissions and
12 | // limitations under the License.
13 |
14 | using System;
15 | using System.Collections.Generic;
16 | using System.Linq;
17 | using System.Net;
18 | using MailKit.Security;
19 | using Serilog.Configuration;
20 | using Serilog.Core;
21 | using Serilog.Events;
22 | using Serilog.Formatting.Display;
23 | using Serilog.Sinks.Email;
24 | // ReSharper disable MemberCanBePrivate.Global
25 |
26 | namespace Serilog;
27 |
28 | ///
29 | /// Adds the WriteTo.Email() extension method to .
30 | ///
31 | public static class LoggerConfigurationEmailExtensions
32 | {
33 | static readonly TimeSpan DefaultBufferingTimeLimit = TimeSpan.FromSeconds(30);
34 | const int DefaultQueueLimit = 10000;
35 |
36 | ///
37 | /// Adds a sink that sends log events via email.
38 | ///
39 | /// The logger configuration.
40 | /// The email address emails will be sent from.
41 | /// The email address emails will be sent to. Multiple addresses can be separated
42 | /// with commas or semicolons.
43 | /// The SMTP email server to use
44 | /// Choose the security applied to the SMTP connection. This enumeration type
45 | /// is supplied by MailKit; see for supported values. The default is
46 | /// .
47 | /// The network credentials to use to authenticate with mailServer
48 | /// A message template describing the format used to write to the sink.
49 | /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".
50 | /// Supplies culture-specific formatting information, or null.
51 | /// The subject, can be a plain string or a template such as {Timestamp} [{Level}] occurred.
52 | /// Gets or sets the port used for the SMTP connection. The default is 25.
53 | /// The minimum level for
54 | /// events passed through the sink. Ignored when is specified.
55 | /// A switch allowing the pass-through minimum level
56 | /// to be changed at runtime.
57 | ///
58 | /// Logger configuration, allowing configuration to continue.
59 | ///
60 | /// A required parameter is null.
61 | public static LoggerConfiguration Email(
62 | this LoggerSinkConfiguration loggerConfiguration,
63 | string from,
64 | string to,
65 | string host,
66 | int port = EmailSinkOptions.DefaultPort,
67 | SecureSocketOptions connectionSecurity = EmailSinkOptions.DefaultConnectionSecurity,
68 | ICredentialsByHost? credentials = null,
69 | string? subject = null,
70 | string? body = null,
71 | IFormatProvider? formatProvider = null,
72 | LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
73 | LoggingLevelSwitch? levelSwitch = null)
74 | {
75 | if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));
76 | if (from == null) throw new ArgumentNullException(nameof(from));
77 | if (to == null) throw new ArgumentNullException(nameof(to));
78 | if (host == null) throw new ArgumentNullException(nameof(host));
79 |
80 | var connectionInfo = new EmailSinkOptions
81 | {
82 | From = from,
83 | To = SplitToAddresses(to),
84 | Host = host,
85 | Port = port,
86 | ConnectionSecurity = connectionSecurity,
87 | Credentials = credentials,
88 | IsBodyHtml = false, // `MessageTemplateTextFormatter` cannot emit valid HTML; the `EmailSinkOptions` overload must be used for this.
89 | };
90 |
91 | if (subject != null)
92 | connectionInfo.Subject = new MessageTemplateTextFormatter(subject, formatProvider);
93 |
94 | if (body != null)
95 | connectionInfo.Body = new MessageTemplateTextFormatter(body, formatProvider);
96 |
97 | return Email(
98 | loggerConfiguration,
99 | connectionInfo,
100 | null,
101 | restrictedToMinimumLevel,
102 | levelSwitch);
103 | }
104 |
105 | ///
106 | /// Adds a sink that sends log events via email.
107 | ///
108 | /// The logger configuration.
109 | /// The connection info used for
110 | /// Optionally, a to control background batching.
111 | /// The minimum level for
112 | /// events passed through the sink. Ignored when is specified.
113 | /// A switch allowing the pass-through minimum level
114 | /// to be changed at runtime.
115 | ///
116 | /// Logger configuration, allowing configuration to continue.
117 | ///
118 | /// A required parameter is null.
119 | public static LoggerConfiguration Email(
120 | this LoggerSinkConfiguration loggerConfiguration,
121 | EmailSinkOptions options,
122 | BatchingOptions? batchingOptions = null,
123 | LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
124 | LoggingLevelSwitch? levelSwitch = null)
125 | {
126 | if (options == null) throw new ArgumentNullException(nameof(options));
127 |
128 | batchingOptions ??= new BatchingOptions
129 | {
130 | // Batching not used by default: fire off an email immediately upon receiving each event.
131 | BatchSizeLimit = 1,
132 | BufferingTimeLimit = DefaultBufferingTimeLimit,
133 | EagerlyEmitFirstEvent = true,
134 | QueueLimit = DefaultQueueLimit,
135 | };
136 |
137 | var transport = new MailKitEmailTransport(options);
138 | var sink = new EmailSink(options, transport);
139 |
140 | return loggerConfiguration.Sink(sink, batchingOptions, restrictedToMinimumLevel, levelSwitch);
141 | }
142 |
143 |
144 | internal static List SplitToAddresses(string? toEmail)
145 | {
146 | return (toEmail ?? "")
147 | .Split(';', ',')
148 | .Select(s => s.Trim())
149 | .Where(s => !string.IsNullOrEmpty(s))
150 | .ToList();
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.Email/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 |
3 | [assembly: InternalsVisibleTo("Serilog.Sinks.Email.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b81894191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066b19485ec")]
4 | [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
5 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.Email/Serilog.Sinks.Email.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Send Serilog events as SMTP email using MailKit.
4 | Serilog Contributors
5 | net462;net471
6 | $(TargetFrameworks);netstandard2.0;net6.0;net8.0;net9.0
7 | serilog;smtp;mailkit
8 | serilog-sink-nuget.png
9 | https://serilog.net/
10 | Apache-2.0
11 |
12 | true
13 | README.md
14 | Serilog
15 | true
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.Email/Sinks/Email/EmailMessage.cs:
--------------------------------------------------------------------------------
1 | // Copyright © Serilog Contributors
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | // http://www.apache.org/licenses/LICENSE-2.0
7 | //
8 | // Unless required by applicable law or agreed to in writing, software
9 | // distributed under the License is distributed on an "AS IS" BASIS,
10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | // See the License for the specific language governing permissions and
12 | // limitations under the License.
13 |
14 | using System.Collections.Generic;
15 |
16 | namespace Serilog.Sinks.Email;
17 |
18 | class EmailMessage(string from, IEnumerable to, string subject, string body, bool isBodyHtml)
19 | {
20 | public string From { get; } = from;
21 |
22 | public string Subject { get; } = subject;
23 |
24 | public string Body { get; } = body;
25 |
26 | public bool IsBodyHtml { get; } = isBodyHtml;
27 |
28 | public IEnumerable To { get; } = to;
29 | }
30 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.Email/Sinks/Email/EmailSink.cs:
--------------------------------------------------------------------------------
1 | // Copyright © Serilog Contributors
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | // http://www.apache.org/licenses/LICENSE-2.0
7 | //
8 | // Unless required by applicable law or agreed to in writing, software
9 | // distributed under the License is distributed on an "AS IS" BASIS,
10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | // See the License for the specific language governing permissions and
12 | // limitations under the License.
13 |
14 | using System;
15 | using System.Collections.Generic;
16 | using System.IO;
17 | using System.Threading.Tasks;
18 | using Serilog.Events;
19 | using System.Linq;
20 | using Serilog.Core;
21 | using Serilog.Formatting;
22 |
23 | namespace Serilog.Sinks.Email;
24 |
25 | class EmailSink : IBatchedLogEventSink, IDisposable
26 | {
27 | readonly EmailSinkOptions _sinkOptions;
28 | readonly IEmailTransport _emailTransport;
29 |
30 | ///
31 | /// Construct a sink emailing with the specified details.
32 | ///
33 | /// Connection information used to construct the SMTP client and mail messages.
34 | /// The email transport to use.
35 | /// connectionInfo
36 | public EmailSink(EmailSinkOptions options, IEmailTransport emailTransport)
37 | {
38 | _sinkOptions = options ?? throw new ArgumentNullException(nameof(options));
39 | _emailTransport = emailTransport ?? throw new ArgumentNullException(nameof(emailTransport));
40 | }
41 |
42 | ///
43 | /// Emit a batch of log events, running asynchronously.
44 | ///
45 | /// The events to emit.
46 | public Task EmitBatchAsync(IReadOnlyCollection events)
47 | {
48 | if (events == null)
49 | throw new ArgumentNullException(nameof(events));
50 |
51 | var body = new StringWriter();
52 |
53 | if (_sinkOptions.Body is IBatchTextFormatter batchTextFormatter)
54 | {
55 | batchTextFormatter.FormatBatch(events, body);
56 | }
57 | else
58 | {
59 | foreach (var logEvent in events)
60 | {
61 | _sinkOptions.Body.Format(logEvent, body);
62 | }
63 | }
64 |
65 | var subject = ComputeMailSubject(_sinkOptions.Subject, events);
66 |
67 | var email = new EmailMessage(
68 | _sinkOptions.From,
69 | _sinkOptions.To,
70 | subject,
71 | body.ToString(),
72 | _sinkOptions.IsBodyHtml);
73 |
74 | return _emailTransport.SendMailAsync(email);
75 | }
76 |
77 | internal static string ComputeMailSubject(ITextFormatter subjectLineFormatter, IEnumerable events)
78 | {
79 | var subject = new StringWriter();
80 | subjectLineFormatter.Format(events.OrderByDescending(e => e.Level).First(), subject);
81 | var subjectAsText = subject.ToString();
82 | var firstLineOfSubject = subjectAsText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
83 | .FirstOrDefault() ?? string.Empty;
84 | return firstLineOfSubject;
85 | }
86 |
87 | public Task OnEmptyBatchAsync()
88 | {
89 | return Task.FromResult(false);
90 | }
91 |
92 | public void Dispose()
93 | {
94 | _emailTransport.Dispose();
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.Email/Sinks/Email/EmailSinkOptions.cs:
--------------------------------------------------------------------------------
1 | // Copyright © Serilog Contributors
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | // http://www.apache.org/licenses/LICENSE-2.0
7 | //
8 | // Unless required by applicable law or agreed to in writing, software
9 | // distributed under the License is distributed on an "AS IS" BASIS,
10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | // See the License for the specific language governing permissions and
12 | // limitations under the License.
13 |
14 | using System;
15 | using System.Collections.Generic;
16 | using System.ComponentModel;
17 | using System.Net;
18 | using MailKit.Security;
19 | using Serilog.Formatting;
20 | using Serilog.Formatting.Display;
21 |
22 | // ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
23 | // ReSharper disable PropertyCanBeMadeInitOnly.Global
24 | // ReSharper disable UnusedAutoPropertyAccessor.Global
25 |
26 | namespace Serilog.Sinks.Email;
27 |
28 | ///
29 | /// Connection information for use by the Email sink.
30 | ///
31 | public sealed class EmailSinkOptions
32 | {
33 | internal const int DefaultPort = 25;
34 | const string DefaultSubject = "Log Messages";
35 | const string DefaultBody = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}";
36 | internal const SecureSocketOptions DefaultConnectionSecurity = SecureSocketOptions.Auto;
37 |
38 | ///
39 | /// Constructs an with default options.
40 | ///
41 | public EmailSinkOptions()
42 | {
43 | }
44 |
45 | ///
46 | /// The email address emails will be sent from.
47 | ///
48 | public string From { get; set; } = null!;
49 |
50 | ///
51 | /// The email address(es) emails will be sent to.
52 | ///
53 | public List To { get; set; } = [];
54 |
55 | ///
56 | /// The SMTP email server to use.
57 | ///
58 | public string Host { get; set; } = null!;
59 |
60 | ///
61 | /// Gets or sets the port used for the SMTP connection. The default is 25.
62 | ///
63 | public int Port { get; set; } = DefaultPort;
64 |
65 | ///
66 | /// Gets or sets the credentials used for authentication.
67 | ///
68 | public ICredentialsByHost? Credentials { get; set; }
69 |
70 | ///
71 | /// The implementation to format email subjects. Specify
72 | /// null to use the default subject. Consider using or
73 | /// Serilog.Expressions templates.
74 | ///
75 | public ITextFormatter Subject { get; set; } = new MessageTemplateTextFormatter(DefaultSubject);
76 |
77 | ///
78 | /// The or implementation
79 | /// to write log entries to email. Specify null to use the default body. Consider using
80 | /// or Serilog.Expressions templates.
81 | ///
82 | public ITextFormatter Body { get; set; } = new MessageTemplateTextFormatter(DefaultBody);
83 |
84 | ///
85 | /// Sets whether the body contents of the email is HTML. Defaults to false.
86 | ///
87 | public bool IsBodyHtml { get; set; }
88 |
89 | ///
90 | /// Choose the security applied to the SMTP connection. This enumeration type is supplied by MailKit; see
91 | /// for supported values. The default is
92 | /// .
93 | ///
94 | public SecureSocketOptions ConnectionSecurity { get; set; } = DefaultConnectionSecurity;
95 |
96 | ///
97 | /// Provides a method that validates server certificates.
98 | ///
99 | public System.Net.Security.RemoteCertificateValidationCallback? ServerCertificateValidationCallback { get; set; }
100 | }
101 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.Email/Sinks/Email/IBatchTextFormatter.cs:
--------------------------------------------------------------------------------
1 | // Copyright © Serilog Contributors
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | // http://www.apache.org/licenses/LICENSE-2.0
7 | //
8 | // Unless required by applicable law or agreed to in writing, software
9 | // distributed under the License is distributed on an "AS IS" BASIS,
10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | // See the License for the specific language governing permissions and
12 | // limitations under the License.
13 |
14 | using System.Collections.Generic;
15 | using System.IO;
16 | using Serilog.Events;
17 | using Serilog.Formatting;
18 |
19 | namespace Serilog.Sinks.Email;
20 |
21 | ///
22 | /// An extension of for handling batches of log events.
23 | /// Use this interface when more control over the formatting of multiple log events is required.
24 | ///
25 | /// Pass an instance for the argument when configuring
26 | /// the sink.
27 | ///
28 | /// This interface might be used to write a header and/or a footer before/after formatting multiple log events,
29 | /// for example to format the events inside a table of an html email. It could also be used to group events by log level.
30 | ///
31 | ///
32 | /// class HtmlTableFormatter : IBatchTextFormatter
33 | /// {
34 | /// public void FormatBatch(IEnumerable<LogEvent> logEvents, TextWriter output)
35 | /// {
36 | /// output.Write("<table>");
37 | /// foreach (var logEvent in logEvents)
38 | /// {
39 | /// Format(logEvent, output);
40 | /// }
41 | /// output.Write("</table>");
42 | /// }
43 | ///
44 | /// public void Format(LogEvent logEvent, TextWriter output)
45 | /// {
46 | /// output.Write("<tr>");
47 | /// using var buffer = new StringWriter();
48 | /// logEvent.RenderMessage(buffer);
49 | /// output.Write(WebUtility.HtmlEncode(buffer.ToString()));
50 | /// output.Write("</tr>");
51 | /// }
52 | /// }
53 | ///
54 | ///
55 | ///
56 | ///
57 | public interface IBatchTextFormatter : ITextFormatter
58 | {
59 | /// Format the log events into the output.
60 | /// The events to format.
61 | /// The output.
62 | void FormatBatch(IEnumerable logEvents, TextWriter output);
63 | }
64 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.Email/Sinks/Email/IEmailTransport.cs:
--------------------------------------------------------------------------------
1 | // Copyright © Serilog Contributors
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | // http://www.apache.org/licenses/LICENSE-2.0
7 | //
8 | // Unless required by applicable law or agreed to in writing, software
9 | // distributed under the License is distributed on an "AS IS" BASIS,
10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | // See the License for the specific language governing permissions and
12 | // limitations under the License.
13 |
14 | using System;
15 | using System.Threading.Tasks;
16 |
17 | namespace Serilog.Sinks.Email;
18 |
19 | interface IEmailTransport : IDisposable
20 | {
21 | Task SendMailAsync(EmailMessage emailMessage);
22 | }
23 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.Email/Sinks/Email/MailKitEmailTransport.cs:
--------------------------------------------------------------------------------
1 | // Copyright © Serilog Contributors
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | // http://www.apache.org/licenses/LICENSE-2.0
7 | //
8 | // Unless required by applicable law or agreed to in writing, software
9 | // distributed under the License is distributed on an "AS IS" BASIS,
10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | // See the License for the specific language governing permissions and
12 | // limitations under the License.
13 |
14 | using System.Linq;
15 | using System.Text;
16 | using System.Threading.Tasks;
17 | using MailKit.Net.Smtp;
18 | using MimeKit;
19 |
20 | namespace Serilog.Sinks.Email;
21 |
22 | class MailKitEmailTransport(EmailSinkOptions options) : IEmailTransport
23 | {
24 | public async Task SendMailAsync(EmailMessage emailMessage)
25 | {
26 | var fromAddress = MailboxAddress.Parse(emailMessage.From);
27 | using var mimeMessage = new MimeMessage();
28 | mimeMessage.From.Add(fromAddress);
29 | mimeMessage.To.AddRange(emailMessage.To.Select(MailboxAddress.Parse));
30 | mimeMessage.Subject = emailMessage.Subject;
31 | mimeMessage.Body = options.IsBodyHtml
32 | ? new BodyBuilder { HtmlBody = emailMessage.Body }.ToMessageBody()
33 | : new BodyBuilder { TextBody = emailMessage.Body }.ToMessageBody();
34 |
35 | using var smtpClient = OpenConnectedSmtpClient();
36 | await smtpClient.SendAsync(mimeMessage);
37 | await smtpClient.DisconnectAsync(quit: true);
38 | }
39 |
40 | SmtpClient OpenConnectedSmtpClient()
41 | {
42 | var smtpClient = new SmtpClient();
43 |
44 | if (string.IsNullOrWhiteSpace(options.Host)) return smtpClient;
45 |
46 | if (options.ServerCertificateValidationCallback != null)
47 | {
48 | smtpClient.ServerCertificateValidationCallback += options.ServerCertificateValidationCallback;
49 | }
50 |
51 | smtpClient.Connect(options.Host, options.Port, options.ConnectionSecurity);
52 |
53 | if (options.Credentials != null)
54 | {
55 | smtpClient.Authenticate(
56 | Encoding.UTF8,
57 | options.Credentials.GetCredential(
58 | options.Host, options.Port, "smtp"));
59 | }
60 | return smtpClient;
61 | }
62 |
63 | public void Dispose()
64 | {
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.Email.Tests/EmailSinkTests.cs:
--------------------------------------------------------------------------------
1 | using Serilog.Debugging;
2 | using Serilog.Events;
3 | using Serilog.Formatting.Display;
4 | using Serilog.Parsing;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 | using Serilog.Configuration;
10 | using Serilog.Sinks.Email.Tests.Support;
11 | using Xunit;
12 | using Xunit.Abstractions;
13 |
14 | namespace Serilog.Sinks.Email.Tests;
15 |
16 | public class EmailSinkTests
17 | {
18 | public EmailSinkTests(ITestOutputHelper outputHelper)
19 | {
20 | SelfLog.Enable(outputHelper.WriteLine);
21 | }
22 |
23 | [Fact(Skip = "Requires a localhost mail server")]
24 | public void Works()
25 | {
26 | var selfLogMessages = new List();
27 | SelfLog.Enable(selfLogMessages.Add);
28 |
29 | using (var emailLogger = new LoggerConfiguration()
30 | .WriteTo.Email(
31 | from: "from@localhost.local",
32 | to: "to@localhost.local",
33 | host: "localhost",
34 | body: "[{Level}] {Message}{NewLine}{Exception}",
35 | subject: "subject")
36 | .CreateLogger())
37 | {
38 | emailLogger.Information("test {test}", "test");
39 | }
40 |
41 | Assert.Equal(Enumerable.Empty(), selfLogMessages);
42 | }
43 |
44 | [Fact(Skip = "Requires a smtp mail server")]
45 | public void WorksMultipleEventsInOneMail()
46 | {
47 | var selfLogMessages = new List();
48 | SelfLog.Enable(selfLogMessages.Add);
49 |
50 | using (var emailLogger = new LoggerConfiguration()
51 | .WriteTo.Email(
52 | from: "from@smtpserver.local",
53 | to: "to@smtpserver.local",
54 | host: "smtpserver.local",
55 | body: "[{Level}] {Message}{NewLine}{Exception}",
56 | subject: "test subject")
57 | .CreateLogger())
58 | {
59 | emailLogger.Information("first test {test}", "test1");
60 | emailLogger.Error("second {test}", "test2");
61 | emailLogger.Fatal("third {test}", "test3");
62 | }
63 |
64 | Assert.Equal(Enumerable.Empty(), selfLogMessages);
65 | }
66 |
67 | [Fact]
68 | public void EmailTransportIsDisposedWhenEmailSinkIsDisposed()
69 | {
70 | var transport = new TestEmailTransport();
71 | var emailSink = CreateDefaultEmailSink(new EmailSinkOptions(), transport);
72 |
73 | emailSink.Dispose();
74 |
75 | Assert.True(transport.IsDisposed);
76 | }
77 |
78 | [Fact]
79 | [UseCulture("en-us")]
80 | public async Task SendEmailIsCorrectlyCalledWhenEventAreLogged()
81 | {
82 | var emailConnectionInfo = new EmailSinkOptions
83 | {
84 | To = ["to@localhost.local"],
85 | From = "from@localhost.local",
86 | Body = new MessageTemplateTextFormatter("[{Level}] {Message}{NewLine}{Exception}"),
87 | Subject = new MessageTemplateTextFormatter("[{Level}] A message")
88 | };
89 |
90 | var transport = new TestEmailTransport();
91 |
92 | var emailSink = CreateDefaultEmailSink(emailConnectionInfo, transport);
93 |
94 | await emailSink.EmitBatchAsync(new[]
95 | {
96 | new LogEvent(
97 | DateTimeOffset.Now,
98 | LogEventLevel.Error,
99 | // ReSharper disable once NotResolvedInText
100 | new ArgumentOutOfRangeException("parameter1", "Message of the exception"),
101 | new MessageTemplate("Subject",
102 | new MessageTemplateToken[]
103 | {
104 | new PropertyToken("Message", "A multiline" + Environment.NewLine + "Message")
105 | })
106 | , Enumerable.Empty())
107 | });
108 | emailSink.Dispose();
109 |
110 | var actual = transport.Sent.Single();
111 |
112 | Assert.Equal("[Error] A multiline" + Environment.NewLine
113 | + "Message" + Environment.NewLine
114 | + "System.ArgumentOutOfRangeException: Message of the exception"
115 | + " (Parameter 'parameter1')"
116 | + Environment.NewLine + "", actual.Body);
117 | Assert.Equal("[Error] A message", actual.Subject);
118 | Assert.Equal("from@localhost.local", actual.From);
119 | Assert.Equal(new[] { "to@localhost.local" }, actual.To);
120 | Assert.False(actual.IsBodyHtml);
121 | }
122 |
123 | [Fact]
124 | public void MultilineMessageCreatesSubjectWithTheFirstLineOnly()
125 | {
126 | var subjectLineFormatter = new MessageTemplateTextFormatter("{Message}", null);
127 |
128 | var logEvents = new[]
129 | {
130 | new LogEvent(DateTimeOffset.Now, LogEventLevel.Error, new Exception("An exception occured"),
131 | new MessageTemplate(@"Subject",
132 | new MessageTemplateToken[]{new PropertyToken("Message", "A multiline" + Environment.NewLine + "Message")})
133 | , Enumerable.Empty())
134 | };
135 | var mailSubject = EmailSink.ComputeMailSubject(subjectLineFormatter, logEvents);
136 |
137 | Assert.Equal("A multiline", mailSubject);
138 | }
139 |
140 | [Fact]
141 | public void WorksWithIBatchTextFormatter()
142 | {
143 | var emailConnectionInfo = new EmailSinkOptions
144 | {
145 | To = ["to@example.com"],
146 | From = "from@localhost.local",
147 | IsBodyHtml = true,
148 | Body = new HtmlTableFormatter()
149 | };
150 |
151 | var emailTransport = new TestEmailTransport();
152 | var sink = new EmailSink(emailConnectionInfo, emailTransport);
153 |
154 | using (var emailLogger = new LoggerConfiguration()
155 | .WriteTo.Sink(sink, new BatchingOptions())
156 | .CreateLogger())
157 | {
158 | emailLogger.Information("Information");
159 | emailLogger.Warning("Warning");
160 | emailLogger.Error("");
161 | }
162 |
163 | var single = emailTransport.Sent.Single();
164 | Assert.True(single.IsBodyHtml);
165 | Assert.Equal("Information
Warning
<Error>
", single.Body);
166 | }
167 |
168 | static EmailSink CreateDefaultEmailSink(EmailSinkOptions options, IEmailTransport transport)
169 | {
170 | var emailSink = new EmailSink(
171 | options,
172 | transport);
173 | return emailSink;
174 | }
175 | }
176 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.Email.Tests/LoggerConfigurationEmailExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Xunit;
3 |
4 | namespace Serilog.Sinks.Email.Tests;
5 |
6 | public class LoggerConfigurationEmailExtensionsTests
7 | {
8 | public static object?[][] GetMailAddressSplitCases()
9 | {
10 | return
11 | [
12 | [null, Array.Empty()],
13 | ["", Array.Empty()],
14 | ["to@localhost", new[] {"to@localhost" }],
15 | ["to@localhost, Example ; Another ", new[] {"to@localhost", "Example ", "Another " }]
16 | ];
17 | }
18 |
19 | [Theory]
20 | [MemberData(nameof(GetMailAddressSplitCases))]
21 | public void SplitsMailAddressesCorrectly(string? to, string[] expected)
22 | {
23 | var actual = LoggerConfigurationEmailExtensions.SplitToAddresses(to);
24 | Assert.Equivalent(expected, actual);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.Email.Tests/Serilog.Sinks.Email.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0;net9.0
5 | true
6 | false
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | all
18 | runtime; build; native; contentfiles; analyzers
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.Email.Tests/Support/HtmlTableFormatter.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.IO;
3 | using System.Net;
4 | using Serilog.Events;
5 |
6 | namespace Serilog.Sinks.Email.Tests.Support;
7 |
8 | class HtmlTableFormatter : IBatchTextFormatter
9 | {
10 | public void FormatBatch(IEnumerable logEvents, TextWriter output)
11 | {
12 | output.Write("");
13 | foreach (var logEvent in logEvents)
14 | {
15 | Format(logEvent, output);
16 | }
17 |
18 | output.Write("
");
19 | }
20 |
21 | public void Format(LogEvent logEvent, TextWriter output)
22 | {
23 | output.Write("");
24 | using var buffer = new StringWriter();
25 | logEvent.RenderMessage(buffer);
26 | output.Write(WebUtility.HtmlEncode(buffer.ToString()));
27 | output.Write("
");
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.Email.Tests/Support/TestEmailTransport.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Threading.Tasks;
3 |
4 | namespace Serilog.Sinks.Email.Tests.Support;
5 |
6 | class TestEmailTransport : IEmailTransport
7 | {
8 | public List Sent { get; } = new();
9 | public bool IsDisposed { get; set; }
10 |
11 | public void Dispose()
12 | {
13 | IsDisposed = true;
14 | }
15 |
16 | public Task SendMailAsync(EmailMessage emailMessage)
17 | {
18 | Sent.Add(emailMessage);
19 | return Task.CompletedTask;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.Email.Tests/Support/UseCultureAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Globalization;
3 | using System.Reflection;
4 | using System.Threading;
5 | using Xunit.Sdk;
6 |
7 | // ReSharper disable MemberCanBePrivate.Global
8 | // ReSharper disable InconsistentNaming
9 |
10 | namespace Serilog.Sinks.Email.Tests.Support;
11 |
12 | // This class courtesy of the xUnit samples at https://github.com/xunit/samples.xunit/blob/main/UseCulture/UseCultureAttribute.cs
13 |
14 | ///
15 | /// Apply this attribute to your test method to replace the
16 | /// and
17 | /// with another culture.
18 | ///
19 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
20 | class UseCultureAttribute : BeforeAfterTestAttribute
21 | {
22 | readonly Lazy _culture;
23 | readonly Lazy _uiCulture;
24 |
25 | CultureInfo? _originalCulture;
26 | CultureInfo? _originalUiCulture;
27 |
28 | ///
29 | /// Replaces the culture and UI culture of the current thread with
30 | ///
31 | ///
32 | /// The name of the culture.
33 | ///
34 | ///
35 | /// This constructor overload uses for both
36 | /// and .
37 | ///
38 | ///
39 | public UseCultureAttribute(string culture)
40 | : this(culture, culture) { }
41 |
42 | ///
43 | /// Replaces the culture and UI culture of the current thread with
44 | /// and
45 | ///
46 | /// The name of the culture.
47 | /// The name of the UI culture.
48 | public UseCultureAttribute(string culture, string uiCulture)
49 | {
50 | _culture = new Lazy(() => new CultureInfo(culture, false));
51 | _uiCulture = new Lazy(() => new CultureInfo(uiCulture, false));
52 | }
53 |
54 | ///
55 | /// Gets the culture.
56 | ///
57 | public CultureInfo Culture => _culture.Value;
58 |
59 | ///
60 | /// Gets the UI culture.
61 | ///
62 | public CultureInfo UICulture => _uiCulture.Value;
63 |
64 | ///
65 | /// Stores the current
66 | /// and
67 | /// and replaces them with the new cultures defined in the constructor.
68 | ///
69 | /// The method under test
70 | public override void Before(MethodInfo methodUnderTest)
71 | {
72 | _originalCulture = Thread.CurrentThread.CurrentCulture;
73 | _originalUiCulture = Thread.CurrentThread.CurrentUICulture;
74 |
75 | Thread.CurrentThread.CurrentCulture = Culture;
76 | Thread.CurrentThread.CurrentUICulture = UICulture;
77 |
78 | CultureInfo.CurrentCulture.ClearCachedData();
79 | CultureInfo.CurrentUICulture.ClearCachedData();
80 | }
81 |
82 | ///
83 | /// Restores the original and
84 | /// to
85 | ///
86 | /// The method under test
87 | public override void After(MethodInfo methodUnderTest)
88 | {
89 | Thread.CurrentThread.CurrentCulture = _originalCulture!;
90 | Thread.CurrentThread.CurrentUICulture = _originalUiCulture!;
91 |
92 | CultureInfo.CurrentCulture.ClearCachedData();
93 | CultureInfo.CurrentUICulture.ClearCachedData();
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/test/TestHarness/Program.cs:
--------------------------------------------------------------------------------
1 | using Serilog;
2 | using Serilog.Debugging;
3 |
4 | SelfLog.Enable(Console.Error);
5 |
6 | Log.Logger = new LoggerConfiguration()
7 | .WriteTo.Email("from@localhost", "to@localhost", "localhost")
8 | .CreateLogger();
9 |
10 | Log.Information("Hello, world!");
11 |
12 | await Log.CloseAndFlushAsync();
13 |
--------------------------------------------------------------------------------
/test/TestHarness/TestHarness.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net9.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------