Skip to content
This repository has been archived by the owner on Jun 14, 2022. It is now read-only.

Commit

Permalink
Move to MailKit and remove jQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
crobibero committed Jul 26, 2020
1 parent 0551dcf commit 4cb576a
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 121 deletions.
172 changes: 95 additions & 77 deletions MediaBrowser.Plugins.SmtpNotifications/Configuration/config.html
Original file line number Diff line number Diff line change
Expand Up @@ -82,100 +82,118 @@
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(pluginId).then(function (config) {
var smtpConfig = config.Options.filter(function (c) {
return userId == c.UserId;
return userId === c.UserId;
})[0] || { Enabled: false };

document.getElementById('chkEnableSMTP').checked = smtpConfig.Enabled;
$('#txtEmailFrom', page).val(smtpConfig.EmailFrom || '');
$('#txtEmailTo', page).val(smtpConfig.EmailTo || '');
$('#txtServer', page).val(smtpConfig.Server || '');
$('#txtPort', page).val(smtpConfig.Port || '');
document.getElementById('chkEnableSSL').checked = smtpConfig.SSL || false;
document.getElementById('chkEnableAuth').checked = smtpConfig.UseCredentials || false;
$('#txtUsername', page).val(smtpConfig.Username || '');
$('#txtPassword', page).val(smtpConfig.Password || '');
page.querySelector('#chkEnableSMTP').checked = smtpConfig.Enabled;
page.querySelector('#txtEmailFrom').value = smtpConfig.EmailFrom || '';
page.querySelector('#txtEmailTo').value = smtpConfig.EmailTo || '';
page.querySelector('#txtServer').value = smtpConfig.Server || '';
page.querySelector('#txtPort').value = smtpConfig.Port || '';
page.querySelector('#chkEnableSSL').checked = smtpConfig.SSL || false;
page.querySelector('#chkEnableAuth').checked = smtpConfig.UseCredentials || false;
page.querySelector('#txtUsername').value = smtpConfig.Username || '';
page.querySelector('#txtPassword').value = smtpConfig.Password || '';

Dashboard.hideLoadingMsg();
});
}

$('.smtpConfigurationPage').on('pageinit', function (event) {
var page = this;
$('#selectUser', page).on('change', function () {
loadUserConfig(page, this.value);
});
document.querySelector('.smtpConfigurationPage')
.addEventListener('pageinit', function(event){

$('#testNotification', page).on('click', function (event) {
Dashboard.showLoadingMsg();
var onError = function () {
require(['alert'], function (alert) {
alert("There was an error sending the test email. Please check your email settings and try again.");
});
};
var page = this;
page.querySelector('#selectUser')
.addEventListener('change', function () {
loadUserConfig(page, this.value);
});

ApiClient.getPluginConfiguration(pluginId).then(function (config) {
if (!config.Options.length) {
Dashboard.hideLoadingMsg();
require(['alert'], function (alert) {
alert("Please configure and save at least one email account.");
page.querySelector('#testNotification')
.addEventListener('click', function (event) {
Dashboard.showLoadingMsg();
var onError = function () {
require(['alert'], function (alert) {
alert("There was an error sending the test email. Please check your email settings and try again.");
});
};

ApiClient.getPluginConfiguration(pluginId).then(function (config) {
if (!config.Options.length) {
Dashboard.hideLoadingMsg();
require(['alert'], function (alert) {
alert("Please configure and save at least one email account.");
});
}

config.Options.map(function (c) {
ApiClient.ajax({
type: "POST",
url: ApiClient.getUrl("Notification/SMTP/Test/" + c.UserId)
}).catch(onError);
});

Dashboard.hideLoadingMsg();
}, onError);

event.preventDefault();
});

document.querySelector('.smtpConfigurationForm')
addEventListener('submit', function (e) {
console.info(".smtpConfigurationForm.submit");
Dashboard.showLoadingMsg();
var form = this;

ApiClient.getPluginConfiguration(pluginId).then(function (config) {
var userId = page.querySelector('#selectUser').value;
var smtpConfig = config.Options.filter(function (c) {
return userId === c.UserId;
})[0];

if (!smtpConfig) {
smtpConfig = {};
config.Options.push(smtpConfig);
}

smtpConfig.UserId = userId;
smtpConfig.Enabled = page.querySelector('#chkEnableSMTP').checked;
smtpConfig.EmailFrom = page.querySelector('#txtEmailFrom').value;
smtpConfig.EmailTo = page.querySelector('#txtEmailTo').value;
smtpConfig.Server = page.querySelector('#txtServer').value;
smtpConfig.Port = page.querySelector('#txtPort').value;
smtpConfig.useCredentials = page.querySelector('#chkEnableAuth').checked;
smtpConfig.SSL = page.querySelector('#chkEnableSSL').checked;
smtpConfig.Username = page.querySelector('#txtUsername').value;
smtpConfig.Password = page.querySelector('#txtPassword').value;

ApiClient.updatePluginConfiguration(pluginId, config)
.then(Dashboard.processPluginConfigurationUpdateResult);
});
}

config.Options.map(function (c) {
ApiClient.ajax({
type: "POST",
url: ApiClient.getUrl("Notification/SMTP/Test/" + c.UserId)
}).catch(onError);

e.preventDefault();
return false;
});

Dashboard.hideLoadingMsg();
}, onError);
});
})

$('.smtpConfigurationForm', page).on('submit', function (e) {
document.querySelector('.smtpConfigurationPage')
.addEventListener('pageshow', function(event){
Dashboard.showLoadingMsg();
var form = this;

ApiClient.getPluginConfiguration(pluginId).then(function (config) {
var userId = $('#selectUser', form).val();
var smtpConfig = config.Options.filter(function (c) {
return userId == c.UserId;
})[0];

if (!smtpConfig) {
smtpConfig = {};
config.Options.push(smtpConfig);
}

smtpConfig.UserId = userId;
smtpConfig.Enabled = document.getElementById('chkEnableSMTP').checked;
smtpConfig.EmailFrom = $('#txtEmailFrom', form).val();
smtpConfig.EmailTo = $('#txtEmailTo', form).val();
smtpConfig.Server = $('#txtServer', form).val();
smtpConfig.Port = $('#txtPort', form).val();
smtpConfig.useCredentials = document.getElementById('chkEnableAuth').checked;
smtpConfig.SSL = document.getElementById('chkEnableSSL').checked;
smtpConfig.Username = $('#txtUsername', form).val();
smtpConfig.Password = $('#txtPassword', form).val();

ApiClient.updatePluginConfiguration(pluginId, config).then(Dashboard.processPluginConfigurationUpdateResult);
var page = this;

ApiClient.getUsers().then(function (users) {
var selUser = page.querySelector('#selectUser');
selUser.innerHTML = users.map(function (user) {
return '<option value="' + user.Id + '">' + user.Name + '</option>';
});
selUser.dispatchEvent(new Event('change', {
bubbles: true,
cancelable: false
}));
});

return false;
});

}).on('pageshow', function (event) {
Dashboard.showLoadingMsg();
var page = this;

ApiClient.getUsers().then(function (users) {
document.getElementById('selectUser').innerHTML = users.map(function (user) {
return '<option value="' + user.Id + '">' + user.Name + '</option>';
});
Dashboard.hideLoadingMsg();
});

Dashboard.hideLoadingMsg();
});
})();
</script>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@

<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<AssemblyVersion>7.0.0.0</AssemblyVersion>
<FileVersion>7.0.0.0</FileVersion>
<AssemblyVersion>8.0.0.0</AssemblyVersion>
<FileVersion>8.0.0.0</FileVersion>
</PropertyGroup>

<ItemGroup>
<None Remove="Configuration\config.html"/>
<EmbeddedResource Include="Configuration\config.html"/>
<None Remove="Configuration\config.html" />
<EmbeddedResource Include="Configuration\config.html" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="MailKit" Version="2.8.0" />
<PackageReference Include="Jellyfin.Data" Version="10.*-*"/>
<PackageReference Include="Jellyfin.Controller" Version="10.*-*"/>
</ItemGroup>
Expand Down
76 changes: 37 additions & 39 deletions MediaBrowser.Plugins.SmtpNotifications/Notifier.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
using System;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Entities;
using MailKit.Net.Smtp;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Plugins.SmtpNotifications.Configuration;
using Microsoft.Extensions.Logging;
using MimeKit;

namespace MediaBrowser.Plugins.SmtpNotifications
{
Expand Down Expand Up @@ -38,48 +37,47 @@ public async Task SendNotification(UserNotification request, CancellationToken c
{
var options = GetOptions(request.User);

using (var mail = new MailMessage(options.EmailFrom, options.EmailTo)
var message = new MimeMessage();
message.From.Add(new MailboxAddress(options.EmailFrom, options.EmailFrom));
message.To.Add(new MailboxAddress(options.EmailTo, options.EmailTo));
message.Subject = "Jellyfin: " + request.Name;
message.Body = new TextPart("plain")
{
Subject = "Jellyfin: " + request.Name,
Body = string.Format("{0}\n\n{1}", request.Name, request.Description)
})
using (var client = new SmtpClient
Text = $"{request.Name}\n\n{request.Description}"
};

using var client = new SmtpClient();
try
{
Host = options.Server,
Port = options.Port,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Timeout = 20000
})
{
if (options.SSL)
{
client.EnableSsl = true;
}

_logger.LogInformation("Sending email {to} with subject {subject}", options.EmailTo, mail.Subject);

if (options.UseCredentials
&& !string.IsNullOrEmpty(options.Username)
&& !string.IsNullOrEmpty(options.Password))
{
client.Credentials = new NetworkCredential(options.Username, options.Password);
}
else
await client.ConnectAsync(options.Server, options.Port, options.SSL, cancellationToken).ConfigureAwait(false);
if (options.UseCredentials)
{
_logger.LogError(
"Cannot use credentials for email to {User} because the username or password is missing",
options.EmailTo);
if (!string.IsNullOrEmpty(options.Username)
&& !string.IsNullOrEmpty(options.Password))
{
await client.AuthenticateAsync(options.Username, options.Password, cancellationToken).ConfigureAwait(false);
}
else
{
_logger.LogError(
"Cannot use credentials for email to {User} because the username or password is missing",
options.EmailTo);
}
}

try
{
await client.SendMailAsync(mail).ConfigureAwait(false);
_logger.LogInformation("Completed sending email {to} with subject {subject}", options.EmailTo, mail.Subject);
}
catch (Exception ex)
_logger.LogInformation("Sending email {to} with subject {subject}", options.EmailTo, message.Subject);
await client.SendAsync(message, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Completed sending email {to} with subject {subject}", options.EmailTo, message.Subject);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending email");
}
finally
{
if (client.IsConnected)
{
_logger.LogError(ex, "Error sending email");
await client.DisconnectAsync(true, cancellationToken).ConfigureAwait(false);
}
}
}
Expand Down
5 changes: 4 additions & 1 deletion build.yaml
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
---
name: "Email"
guid: "cfa0f7f4-4155-4d71-849b-d6598dc4c5bb"
version: "7.0.0.0"
version: "8.0.0.0"
targetAbi: "10.6.0.0"
owner: "jellyfin"
overview: "Send SMTP email notifications"
description: "Send SMTP email notifications"
category: "Notifications"
artifacts:
- "MediaBrowser.Plugins.SmtpNotifications.dll"
- "BouncyCastle.Crypto.dll"
- "MailKit.dll"
- "MimeKit.dll"
changelog: >
changelog

0 comments on commit 4cb576a

Please sign in to comment.