Skip to content

Commit

Permalink
Отправка через IMAP.
Browse files Browse the repository at this point in the history
 * Добавлена отправка через IMAP.
 * Исправлены мелкие ошибки.
 * Рефакторинг.
  • Loading branch information
dmpas committed Dec 18, 2016
1 parent ccb4bf0 commit 9365ffc
Show file tree
Hide file tree
Showing 9 changed files with 271 additions and 85 deletions.
16 changes: 16 additions & 0 deletions MailComponent/Mail/IMailSender.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/

namespace OneScript.InternetMail
{
public interface IMailSender
{
void Logon(InternetMailProfile profile);
void Logoff();
void Send(InternetMailMessage message, InternetMailTextProcessing processText);
}
}
9 changes: 7 additions & 2 deletions MailComponent/Mail/ImapReceiver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ This Source Code Form is subject to the terms of the

namespace OneScript.InternetMail
{
public class ImapReceiver : IMailReceiver, IDisposable
public class ImapReceiver : IMailReceiver, IMailSender, IDisposable
{
private readonly ImapClient client = new ImapClient();
private InternetMailProfile _profile;
Expand Down Expand Up @@ -225,7 +225,7 @@ public ArrayImpl GetIdentifiers(ArrayImpl identifiers, StructureImpl filter)
var headerWithUid = ivHeaderWithUid as InternetMailMessage;
var Id = headerWithUid.Uid.Get(0);

if (identifiers == null || identifiers.Find(Id).DataType != DataType.Undefined)
if (identifiers == null || identifiers.Find(Id).DataType == DataType.Undefined)
result.Add(Id);
}

Expand Down Expand Up @@ -311,5 +311,10 @@ public void Dispose()
Logoff();
}

public void Send(InternetMailMessage message, InternetMailTextProcessing processText)
{
var messageToSend = message.CreateNativeMessage(processText);
_currentFolder.Append(messageToSend);
}
}
}
38 changes: 24 additions & 14 deletions MailComponent/Mail/InternetMail.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class InternetMail : AutoContext<InternetMail>, IDisposable
{
private InternetMailProfile _profile;

private SmtpClient smtpClient = new SmtpClient();
private readonly SmtpSender smtpClient = new SmtpSender();
private IMailReceiver receiver;
private string _currentMailbox = "";
private string _mailboxDelimiterCharacter = "";
Expand Down Expand Up @@ -60,19 +60,12 @@ public string CurrentMailbox

private void LogonSmtp()
{
SecureSocketOptions options = SecureSocketOptions.Auto;
smtpClient.Timeout = _profile.Timeout * 1000;
smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
smtpClient.Connect(_profile.SmtpServerAddress, _profile.GetSmtpPort(), options);

if (_profile.SmtpUser != "")
smtpClient.Authenticate(_profile.SmtpUser, _profile.SmtpPassword);
smtpClient.Logon(_profile);
}

private void LogoffSmtp()
{
if (smtpClient.IsConnected)
smtpClient.Disconnect(true);
smtpClient.Logoff();
}

#endregion
Expand All @@ -83,7 +76,9 @@ public void Logon(InternetMailProfile profile, InternetMailProtocol receiveMailP
_profile = profile;

if (!string.IsNullOrEmpty(_profile.SmtpServerAddress) && !_profile.Pop3BeforeSmtp)
{
LogonSmtp();
}

switch (receiveMailProtocol)
{
Expand Down Expand Up @@ -130,12 +125,17 @@ public void Send(InternetMailMessage message,
throw new RuntimeException("Недопустимо указывать POP3 в качестве протокола отправки почты!");
}

var messageToSend = message.CreateNativeMessage(processText);

IMailSender sender = null;
if (protocol == InternetMailProtocol.Smtp)
sender = smtpClient;
else if (protocol == InternetMailProtocol.Imap)
{
smtpClient.Send(messageToSend);
sender = receiver as ImapReceiver;
if (sender == null)
throw new RuntimeException("Соединение IMAP не установлено!");
}

sender?.Send(message, processText);
}

[ContextMethod("ПолучитьЗаголовки", "GetHeaders")]
Expand All @@ -162,46 +162,55 @@ public void DeleteMessages(ArrayImpl dataToDelete)
receiver?.DeleteMessages(dataToDelete);
}

[ContextMethod("ПолучитьПочтовыеЯщики", "GetMailBoxes")]
public ArrayImpl GetMailboxes()
{
return receiver?.GetMailboxes();
}

[ContextMethod("ПолучитьПочтовыеЯщикиПоПодписке", "GetMailBoxesBySubscription")]
public ArrayImpl GetMailboxesBySubscription()
{
return receiver?.GetMailboxesBySubscription();
}

[ContextMethod("ПодписатьсяНаПочтовыйЯщик", "SubscribeToMailbox")]
public void SubscribeToMailbox(string name)
{
receiver?.SubscribeToMailbox(name);
}

[ContextMethod("ОтменитьПодпискуНаПочтовыйЯщик", "UnsubscribeFromMailbox")]
public void UnsubscribeFromMailbox(string name)
{
receiver?.UnsubscribeFromMailbox(name);
}

[ContextMethod("ОтменитьУдалениеСообщений", "UndeleteMessages")]
public void UndeleteMessages(ArrayImpl deletedData)
{
receiver?.UndeleteMessages(deletedData);
}

[ContextMethod("ОчиститьУдаленныеСообщения", "ClearDeletedMessages")]
public void ClearDeletedMessages()
{
receiver?.ClearDeletedMessages();
}

[ContextMethod("ПереименоватьПочтовыйЯщик", "RenameMailbox")]
public void RenameMailbox(string name, string newName)
{
receiver?.RenameMailbox(name, newName);
}

[ContextMethod("СоздатьПочтовыйЯщик", "CreateMailbox")]
public void CreateMailbox(string name)
{
receiver?.CreateMailbox(name);
}

[ContextMethod("УдалитьПочтовыйЯщик", "DeleteMailbox")]
public void DeleteMailbox(string name)
{
receiver?.DeleteMailbox(name);
Expand All @@ -215,7 +224,8 @@ public ArrayImpl Get(bool? deleteMessages = null, ArrayImpl ids = null, bool? ma

public void Dispose()
{
((IDisposable)smtpClient).Dispose();
smtpClient.Dispose();
(receiver as IDisposable)?.Dispose();
}

[ScriptConstructor]
Expand Down
3 changes: 2 additions & 1 deletion MailComponent/Mail/Pop3Receiver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public ArrayImpl GetIdentifiers(ArrayImpl identifiers = null, StructureImpl filt
{
var Id = ValueFactory.Create(uid);

if (identifiers == null || identifiers.Find(Id).DataType != DataType.Undefined)
if (identifiers == null || identifiers.Find(Id).DataType == DataType.Undefined)
result.Add(Id);
}

Expand Down Expand Up @@ -165,6 +165,7 @@ public ArrayImpl Get(bool deleteMessages, ArrayImpl ids, bool markAsRead)
if (deleteMessages && processedMessages.Count > 0)
{
client.DeleteMessages(processedMessages);
Relogon();
}

return result;
Expand Down
47 changes: 47 additions & 0 deletions MailComponent/Mail/SmtpSender.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using System;
using MailKit.Net.Smtp;
using MailKit.Security;

namespace OneScript.InternetMail
{
public class SmtpSender : IMailSender, IDisposable
{

private readonly SmtpClient _client = new SmtpClient();

public void Logoff()
{
if (_client.IsConnected)
_client.Disconnect(true);
}

public void Logon(InternetMailProfile profile)
{
SecureSocketOptions options = SecureSocketOptions.Auto;
_client.Timeout = profile.Timeout * 1000;
_client.ServerCertificateValidationCallback = (s, c, h, e) => true;
_client.Connect(profile.SmtpServerAddress, profile.GetSmtpPort(), options);

if (profile.SmtpUser != "")
_client.Authenticate(profile.SmtpUser, profile.SmtpPassword);
}

public void Send(InternetMailMessage message, InternetMailTextProcessing processText)
{
var messageToSend = message.CreateNativeMessage(processText);
_client.Send(messageToSend);
}

public void Dispose()
{
Logoff();
}

}
}
2 changes: 2 additions & 0 deletions MailComponent/MailComponent.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@
<Compile Include="Mail\NotSupportedInSelectedProtocol.cs" />
<Compile Include="Mail\ImapReceiver.cs" />
<Compile Include="Mail\ImapSearchFilter.cs" />
<Compile Include="Mail\IMailSender.cs" />
<Compile Include="Mail\SmtpSender.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
Expand Down
2 changes: 1 addition & 1 deletion MailComponent/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion("1.0.1.*")]
[assembly: AssemblyVersion("1.0.2.*")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
Expand Down
Loading

0 comments on commit 9365ffc

Please sign in to comment.