DS7_HYRD
hanxuntao 12 months ago
parent 026208701e
commit 3474b07bcd

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<appSettings>
<!-- 服务的名称、显示名称 -->
<add key="ServiceName" value="D7DJYMQ" />
<add key="ServiceDisplayName" value="大简云日期回推" />
<add key="DJYMQURL" value="amqp://xgs_test:xgs_test123@60.209.125.238:40101" />
<add key="virtualhost" value="XGSTEST" />
<add key="MQExchangeName" value="" />
<add key="MQQueueName" value="cr_cuttime_etd" />
<add key="MAILSENDACCOUNT" value=" " />
<add key="MAILSENDPASSWORD" value="" />
<add key="MAILSENDSERVICE" value="" />
<add key="MAILSENDPORT" value="" />
<add key="MAILISSSL" value="" />
<add key="ConnectionString" value="Data Source=ds-hxt;Initial Catalog=SHIPPINGWEB_qj;User ID=sa;Password=Ds20040201" />
<add key="BSSQL" value=" ETD&gt;=GETDATE()" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<connectionStrings>
<!--本地开发
<add name="DongShengDB" connectionString="Data Source=60.209.125.238,52314;Initial Catalog=ShippingWeb_JHCSK;Persist Security Info=True;User ID=sa;Password=Ds20040201" providerName="System.Data.SqlClient" />
-->
<!--本地开发 -->
<add name="DS6DB" connectionString="Data Source=60.209.125.238,32009;Initial Catalog=HECHUAN;Persist Security Info=True;User ID=sa;Password=sa@djy.net" providerName="System.Data.SqlClient" />
<!--实际地址
<add name="DS6DB" connectionString="Data Source=60.209.125.238,32009;Initial Catalog=HECHUAN;Persist Security Info=True;User ID=sa;Password=sa@djy.net" providerName="System.Data.SqlClient" />
-->
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<quartz>
<add key="quartz.scheduler.instanceName" value="ServerScheduler" />
<add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
<add key="quartz.threadPool.threadCount" value="50" />
<add key="quartz.threadPool.threadPriority" value="2" />
<add key="quartz.plugin.xml.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz" />
<add key="quartz.plugin.xml.fileNames" value="~/quartz_jobs.xml" />
<add key="quartz.jobStore.misfireThreshold" value="30000" />
<add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz" />
</quartz>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
</configuration>

@ -0,0 +1,171 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.props" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B70AD9DA-65F3-4E4D-BA22-928100F9292B}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>D7DJYMQ</RootNamespace>
<AssemblyName>D7DJYMQ</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<IsWebBootstrapper>false</IsWebBootstrapper>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>1</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<PublishWizardCompleted>true</PublishWizardCompleted>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ManifestCertificateThumbprint>DC505909EE57A206168428C0B78FC9DFF308697E</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<ManifestKeyFile>DSWeb.DJYMQ_TemporaryKey.pfx</ManifestKeyFile>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>true</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<SignManifests>true</SignManifests>
</PropertyGroup>
<ItemGroup>
<Reference Include="Common.Logging, Version=3.3.1.0, Culture=neutral, PublicKeyToken=af08829b84f0328e, processorArchitecture=MSIL">
<HintPath>..\packages\Common.Logging.3.3.1\lib\net40\Common.Logging.dll</HintPath>
</Reference>
<Reference Include="Common.Logging.Core, Version=3.3.1.0, Culture=neutral, PublicKeyToken=af08829b84f0328e, processorArchitecture=MSIL">
<HintPath>..\packages\Common.Logging.Core.3.3.1\lib\net40\Common.Logging.Core.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.1.2.10\lib\2.0\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Quartz, Version=2.6.2.0, Culture=neutral, PublicKeyToken=f6b8c98a402cc8a4, processorArchitecture=MSIL">
<HintPath>..\packages\Quartz.2.6.2\lib\net40\Quartz.dll</HintPath>
</Reference>
<Reference Include="RabbitMQ.Client, Version=6.0.0.0, Culture=neutral, PublicKeyToken=89e7d7c5feba84ce, processorArchitecture=MSIL">
<HintPath>..\packages\RabbitMQ.Client.6.2.2\lib\net461\RabbitMQ.Client.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Threading.Channels, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Channels.4.7.1\lib\net461\System.Threading.Channels.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="Topshelf, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b800c4cfcdeea87b, processorArchitecture=MSIL">
<HintPath>..\packages\Topshelf.4.3.0\lib\net452\Topshelf.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="DS7Date.cs" />
<Compile Include="DsSendMail.cs" />
<Compile Include="JobListener.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="quartz_jobs.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<Content Include="log4net.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="DSWeb.DJYMQ_TemporaryKey.pfx" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Content Include="说明.txt" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.7.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.7.2 %28x86 和 x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.4\build\EntityFramework.props'))" />
<Error Condition="!Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.4\build\EntityFramework.targets'))" />
</Target>
<Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.targets" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" />
</Project>

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishUrlHistory>publish\</PublishUrlHistory>
<InstallUrlHistory />
<SupportUrlHistory />
<UpdateUrlHistory />
<BootstrapperUrlHistory />
<ErrorReportUrlHistory />
<FallbackCulture>zh-CN</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles>
</PropertyGroup>
<PropertyGroup>
<EnableSecurityDebugging>false</EnableSecurityDebugging>
</PropertyGroup>
</Project>

@ -0,0 +1,222 @@
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Topshelf;
namespace D7DJYMQ
{
public class DS7Date : ServiceControl
{
private static string MQURL = ConfigurationManager.AppSettings["DJYMQURL"];
private static string connStr = ConfigurationManager.AppSettings["ConnectionString"];
private static string virtualhost = ConfigurationManager.AppSettings["virtualhost"];
private static string ExchangeName = ConfigurationManager.AppSettings["MQExchangeName"];
private static string QueueName = ConfigurationManager.AppSettings["MQQueueName"];
private static string MAILSENDACCOUNT = ConfigurationManager.AppSettings["MAILSENDACCOUNT"];
private static string MAILSENDPASSWORD = ConfigurationManager.AppSettings["MAILSENDPASSWORD"];
private static string MAILSENDSERVICE = ConfigurationManager.AppSettings["MAILSENDSERVICE"];
private static string MAILSENDPORT = ConfigurationManager.AppSettings["MAILSENDPORT"];
private static string MAILISSSL = ConfigurationManager.AppSettings["MAILISSSL"];
private static string MAILTITLE = ConfigurationManager.AppSettings["MAILTITLE"];
private static string BSSQL = ConfigurationManager.AppSettings["BSSQL"];
private static IConnection mqConn;
private static ILog logger = LogManager.GetLogger("DS7Date");
public bool Start(HostControl hostControl)
{
logger.Debug($"启动接收大简云订舱数据回推");
var CompanyQueueName = QueueName;
ConnectionFactory factory = new ConnectionFactory();
factory.Uri = new Uri(MQURL);
//factory.UserName = "xgs_test";
//factory.Password = "xgs_test123";
factory.VirtualHost = virtualhost;
mqConn = factory.CreateConnection();
IModel model = mqConn.CreateModel();
//model.ExchangeDeclare(ExchangeName, ExchangeType.Direct);
model.QueueDeclare(CompanyQueueName, false, false, false, null);
//model.QueueBind(CompanyQueueName, ExchangeName, QueueName);
var consumer = new EventingBasicConsumer(model);
consumer.Received += (ch, ea) =>
{
var body = ea.Body;
var strBody = Encoding.UTF8.GetString(body.ToArray());
logger.Debug($"收到简云截单日期数据回推消息:{strBody}");
try
{
//回写数据
var dateback = JsonConvert.DeserializeAnonymousType(strBody, new { vessel = string.Empty, voyage = string.Empty, ship_agency = string.Empty, cut_off_time = string.Empty, etd = string.Empty });
if (!string.IsNullOrEmpty(dateback.vessel) && !string.IsNullOrEmpty(dateback.voyage) && !string.IsNullOrEmpty(dateback.ship_agency) && !string.IsNullOrEmpty(dateback.cut_off_time))
{
using (SqlConnection dbcon = new SqlConnection(connStr))
{
dbcon.Open();
string maildescrption = "";
var FORWARDER = GetCustEdi(dbcon, dateback.ship_agency);
var SendMailList = new List<SendMail>();
if (!string.IsNullOrEmpty(FORWARDER))
{
var opseaelist = GetBs(dbcon, "VESSEL='" + dateback.vessel + "' AND VOYNO='" + dateback.voyage + "' and FORWARDER='" + FORWARDER + "'");
if (opseaelist != null && opseaelist.Count != 0)
{
var opemail = "";
foreach (var opseae in opseaelist)
{
var tastStr = $" update op_seae set CLOSEDOCDATE='{dateback.cut_off_time}' where BSNO='{opseae.BSNO}' ";
SqlCommand cmdtast = new SqlCommand(tastStr, dbcon);
cmdtast.ExecuteNonQuery();
logger.Debug($"已更新截单日期{dateback.cut_off_time},{opseae.MBLNO},{opseae.BSNO}");
var sendmail = SendMailList.Find(x => x.OP == opseae.OP);
if (sendmail != null)
{
sendmail.MAILDESCRIPTION = sendmail.MAILDESCRIPTION + Environment.NewLine + opseae.MBLNO;
}
else
{
var newsendmail = new SendMail();
newsendmail.OP = opseae.OP;
newsendmail.MAIL = opseae.MAIL;
newsendmail.MAILDESCRIPTION = opseae.MBLNO;
SendMailList.Add(newsendmail);
}
}
}
}
else
{
logger.Debug($"{dateback.ship_agency}没有找到对应的订舱代理");
}
if (SendMailList != null && SendMailList.Count != 0)
{
foreach (var SendMail in SendMailList)
{
SendEmail se = new SendEmail(SendMail.MAIL, MAILSENDACCOUNT, "", "", "截港日期自动更新", SendMail.MAILDESCRIPTION, false);
se.SetSmtp(MAILSENDACCOUNT, MAILSENDPASSWORD, MAILSENDSERVICE, Convert.ToInt16(MAILSENDPORT), false, System.Net.Mail.MailPriority.Normal); //必须在所有参数设置完后调用此方法
logger.Debug($"已给操作{SendMail.OP}发送邮件{SendMail.MAIL}{SendMail.MAILDESCRIPTION}");
}
}
}
}
}
catch (Exception ex)
{
logger.Error($"处理简云订舱数据回推时出错:" + ex.Message);
logger.Error(ex.Message);
logger.Error(ex.StackTrace);
}
};
model.BasicConsume(CompanyQueueName, true, consumer);
return true;
}
public bool Stop(HostControl hostControl)
{
// 结束
logger.Debug("停止运行");
//StdSchedulerFactory.GetDefaultScheduler().Shutdown();
if (mqConn != null && mqConn.IsOpen)
{
mqConn.Close();
mqConn = null;
}
return true;
}
public class MsOpSeae
{
public string BSNO { get; set; }
public string MBLNO { get; set; }
public string OP { get; set; }
public string MAIL { get; set; }
}
public class SendMail
{
public string OP { get; set; }
public string MAIL { get; set; }
public string MAILDESCRIPTION { get; set; }
}
static public List<MsOpSeae> GetBs(SqlConnection dbcon, string constr)
{
var opseaeList = new List<MsOpSeae>();
var strSql = new StringBuilder();
strSql.Append("select BSNO,MBLNO,OP,FORWARDER,(SELECT TOP 1 EMAIL1 FROM VW_user WHERE SHOWNAME=op_seae.OP) EMAIL from op_seae where " + constr);
strSql.Append(" ORDER BY OP ");
SqlDataAdapter adapter = new SqlDataAdapter(strSql.ToString(), dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
var opseae = new MsOpSeae();
opseae.BSNO = Convert.ToString(row["BSNO"].ToString());
opseae.MBLNO = Convert.ToString(row["MBLNO"].ToString());
opseae.OP = Convert.ToString(row["OP"].ToString());
opseae.MAIL = Convert.ToString(row["EMAIL"].ToString());
opseaeList.Add(opseae);
}
}
return opseaeList;
}
static public string GetCustEdi(SqlConnection dbcon, string constr)
{
string result = "";
var strSql = new StringBuilder();
strSql.Append("select CUST from code_cust_edi where EDINAME='DJY' AND EDICODE='" + constr + "'");
SqlDataAdapter adapter = new SqlDataAdapter(strSql.ToString(), dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
result = Convert.ToString(row["CUST"].ToString());
}
}
return result;
}
}
}

File diff suppressed because one or more lines are too long

@ -0,0 +1,359 @@
using System;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Globalization;
using System.Linq;
namespace D7DJYMQ
{
/// <summary>
/// 邮件发送类
/// </summary>
public class SendEmail
{
private MailMessage mailMessage = new MailMessage(); //实例化一个邮件类
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="toAddresses">收件人地址(多个以,号分开)</param>
/// <param name="fromAddress">发件人地址</param>
/// <param name="title">主题</param>
/// <param name="body">正文</param>
public SendEmail(string toAddresses, string fromAddress, string title, string body)
: this(toAddresses, fromAddress, "", "", title, body, false)
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="toAddress">收件人地址</param>
/// <param name="fromAddress">发件人地址</param>
/// <param name="toName">收件人名字</param>
/// <param name="fromName">发件人姓名</param>
/// <param name="title">主题</param>
/// <param name="body">正文</param>
/// <param name="isBodyHtml">正文是否为html格式</param>
public SendEmail(string toAddress, string fromAddress, string toName, string fromName, string title, string body, bool isBodyHtml)
{
mailMessage.From = new MailAddress(fromAddress, fromName, Encoding.GetEncoding(936));
if (toName.Equals(""))
mailMessage.To.Add(toAddress);
else
mailMessage.To.Add(new MailAddress(toAddress, toName, Encoding.GetEncoding(936)));
mailMessage.Subject = title;
mailMessage.SubjectEncoding = Encoding.GetEncoding(936);
mailMessage.Body = body;
mailMessage.IsBodyHtml = isBodyHtml;
mailMessage.BodyEncoding = Encoding.GetEncoding(936);
}
#endregion
/// <summary>
/// 设置SMTP并且将邮件发送出去
/// 所有参数都设置完成后再调用该方法
/// </summary>
/// <param name="password">发件人密码</param>
/// <param name="smtpHost">SMTP服务器地址</param>
public void SetSmtp(string password, string smtpHost)
{
SetSmtp(mailMessage.From.Address, password, smtpHost, 25, false, MailPriority.Normal);
}
/// <summary>
/// 设置SMTP并且将邮件发送出去
/// 所有参数都设置完成后再调用该方法
/// </summary>
/// <param name="address">发件人地址必须为真实有效的email地址</param>
/// <param name="password">发件人密码</param>
/// <param name="smtpHost">SMTP服务器地址</param>
/// <param name="smtpPort">SMTP服务器的端口</param>
/// <param name="isEnableSsl">SMTP服务器是否启用SSL加密</param>
/// <param name="priority">邮件的优先级</param>
public void SetSmtp(string address, string password, string smtpHost, int smtpPort, bool isEnableSsl, MailPriority priority)
{
SmtpClient smtp = new SmtpClient(smtpHost,smtpPort);
// smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
// smtp.UseDefaultCredentials = true;
//if (isEnableSsl)
//{
// smtp.UseDefaultCredentials = true;
// System.Net.NetworkCredential nc = new System.Net.NetworkCredential(address, password);
// smtp.Credentials = nc.GetCredential(smtpHost, smtpPort, "NTLM");
//}
//else
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(address, password);
smtp.Credentials = nc;
//smtp.Credentials = new NetworkCredential(address, password);
//smtp.Host = smtpHost;
//smtp.Port = smtpPort;
smtp.EnableSsl = isEnableSsl;
// smtp.UseDefaultCredentials = true;
// mailMessage.Priority = priority;
try
{
smtp.Send(mailMessage); //发送邮件
}
catch (Exception e)
{
smtp.Dispose();
}
finally
{
smtp.Dispose();
}
smtp.Dispose();
}
class Mailinfo {
public SendEmail se { get; set; }
public string address { get; set; }
public string password { get; set; }
public string smtpHost { get; set; }
public int smtpPort { get; set; }
public bool isEnableSsl { get; set; }
public MailPriority priority { get; set; }
public Mailinfo(SendEmail se, string address, string password, string smtpHost, int smtpPort, bool isEnableSsl, MailPriority priority)
{
this.se = se;
this.address = address;
this.password = password;
this.smtpHost = smtpHost;
this.smtpPort = smtpPort;
this.isEnableSsl = isEnableSsl;
this.priority = priority;
}
}
class ThreadMail
{
public void FuncSend(object o)
{
Mailinfo Mailinfo = o as Mailinfo;
Mailinfo.se.SetSmtp(Mailinfo.address, Mailinfo.password, Mailinfo.smtpHost, Mailinfo.smtpPort, Mailinfo.isEnableSsl, Mailinfo.priority);
}
}
public void SetSmtp_thread( string address, string password, string smtpHost, int smtpPort, bool isEnableSsl, MailPriority priority) {
ThreadMail tmail = new ThreadMail();
//有参调用实例方法ParameterizedThreadStart是一个委托input为object,返回值为void
Thread thread1 = new Thread(new ParameterizedThreadStart(tmail.FuncSend));
Mailinfo mi = new Mailinfo(this, address, password, smtpHost, smtpPort, isEnableSsl, priority);
thread1.Start(mi);
}
#region //设置邮件地址
/// <summary>
/// 设置更多收件人
/// </summary>
/// <param name="toAddresses">收件人地址</param>
public void SetMoreToAddress(string toAddresses)
{
mailMessage.To.Add(toAddresses);
}
/// <summary>
/// 设置更多收件人
/// </summary>
/// <param name="toAddresses">收件人地址</param>
/// <param name="toName">收件人名字</param>
public void SetMoreToAddress(string toAddress, string toName)
{
mailMessage.To.Add(new MailAddress(toAddress, toName, Encoding.GetEncoding(936)));
}
/// <summary>
/// 设置抄送者(多个以,号分开)
/// </summary>
/// <param name="ccAddresses">抄送者地址</param>
public void SetCarbonCopyFor(string ccAddresses)
{
mailMessage.CC.Add(ccAddresses);
}
/// <summary>
/// 设置抄送者
/// </summary>
/// <param name="ccAddress">抄送者地址</param>
/// <param name="ccName">抄送者名字</param>
public void SetCarbonCopyFor(string ccAddress, string ccName)
{
mailMessage.Bcc.Add(new MailAddress(ccAddress, ccName, Encoding.GetEncoding(936)));
}
/// <summary>
/// 设置密送者(多个以,号分开)
/// </summary>
/// <param name="bccAddresses">密送者</param>
public void SetBlindCarbonCopyFor(string bccAddresses)
{
mailMessage.Bcc.Add(bccAddresses);
}
/// <summary>
/// 设置密送者
/// </summary>
/// <param name="bccAddress">密送者</param>
/// <param name="bccName">密送者名字</param>
public void SetBlindCarbonCopyFor(string bccAddress, string bccName)
{
mailMessage.Bcc.Add(new MailAddress(bccAddress, bccName, Encoding.GetEncoding(936)));
}
#endregion
#region 添加附件
/// <summary>
/// 添加附件(自动识别文件类型)
/// </summary>
/// <param name="fileName">单个文件的路径</param>
public void Attachments(string fileName)
{
mailMessage.Attachments.Add(new Attachment(fileName));
}
/// <summary>
/// 添加附件默认为富文本RTF格式
/// </summary>
/// <param name="fileName">单个文件的路径</param>
public void AttachmentsForRTF(string fileName)
{
mailMessage.Attachments.Add(new Attachment(fileName, MediaTypeNames.Application.Rtf));
}
//public void SaveToEml(string emlFileAbsolutePath)
//{
// const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
// using (MemoryStream ms = new MemoryStream())
// {
//     Assembly assembly = typeof(System.Net.Mail.SmtpClient).Assembly;
//     Type tMailWriter = assembly.GetType("System.Net.Mail.MailWriter");
//     object mailWriter = Activator.CreateInstance(tMailWriter, flags, null, new object[] { ms }, CultureInfo.InvariantCulture);
// mailMessage.GetType().GetMethod("Send", flags).Invoke(mailMessage, new object[] { mailWriter, true });
//     File.WriteAllText(emlFileAbsolutePath, System.Text.Encoding.Default.GetString(ms.ToArray()), System.Text.Encoding.Default);
// }
//}
public struct MailBillType
{
public const string = "EDI";
public const string VGM = "VGM";
}
public struct MailInfo {
public const string _ = "DSFTP_EDI_FTP_EDIPATH";
public const string VGM_ = "DSFTP_EDI_FTP_VGMPATH";
public const string __ = "申请发送 ";
public const string __ = "舱单发送-";
public const string VGM__ = "申请发送VGM-";
public const string VGM__ = "VGM发送-";
}
public void SaveToEml(string emlFileAbsolutePath, string billtype)
{
var assembly = typeof(SmtpClient).Assembly;
var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
using (var memoryStream = new MemoryStream())
{
// Get reflection info for MailWriter contructor
var mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
// Construct MailWriter object with our FileStream
var mailWriter = mailWriterContructor.Invoke(new object[] { memoryStream });
// Get reflection info for Send() method on MailMessage
var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
//20210622 标题 按GB2312转base64
var mailhead = "";
var ftphead = "";
if(billtype== MailBillType.)
{
mailhead = MailInfo.__;
ftphead = MailInfo.__;
}
if (billtype == MailBillType.VGM)
{
mailhead = MailInfo.VGM__;
ftphead = MailInfo.VGM__;
}
string title = Convert.ToBase64String(System.Text.Encoding.GetEncoding(936).GetBytes(mailMessage.Subject.Replace(mailhead, ftphead)));
var codedtitle= "=?GB2312?B?"+title+"?=";
// Call method passing in MailWriter
sendMethod.Invoke(mailMessage, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
// Finally get reflection info for Close() method on our MailWriter
var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
// Call close method
closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
var _str = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()).Replace(mailMessage.Subject, codedtitle);
File.WriteAllText(emlFileAbsolutePath, _str, System.Text.Encoding.Default);
//return Encoding.ASCII.GetString(memoryStream.ToArray());
}
}
public MailMessage getMailMessage() {
return mailMessage;
}
#endregion
/// <summary>
/// 将MailMessage保存为eml文件
/// </summary>
/// <param name="msg">待保存的具有内容的MailMessage</param>
/// <param name="emlFileAbsolutePath">保存后的eml文件的路径</param>
public void SaveToEml(string emlFileAbsolutePath)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
using (MemoryStream ms = new MemoryStream())
{
Assembly assembly = typeof(System.Net.Mail.SmtpClient).Assembly;
Type tMailWriter = assembly.GetType("System.Net.Mail.MailWriter");
object mailWriter = Activator.CreateInstance(tMailWriter, flags, null, new object[] { ms }, CultureInfo.InvariantCulture);
mailMessage.GetType().GetMethod("Send", flags).Invoke(mailMessage, new object[] { mailWriter, true });
File.WriteAllText(emlFileAbsolutePath, System.Text.Encoding.Default.GetString(ms.ToArray()), System.Text.Encoding.Default);
}
}
}
}

@ -0,0 +1,126 @@
using log4net;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSWeb.BillCenter.Service
{
public class JobListener : ISchedulerListener
{
private ILog logger = LogManager.GetLogger("JobListener");
public void JobAdded(IJobDetail jobDetail)
{
logger.Debug($"Job被添加{jobDetail.JobType}");
}
public void JobDeleted(JobKey jobKey)
{
}
public void JobPaused(JobKey jobKey)
{
}
public void JobResumed(JobKey jobKey)
{
}
public void JobScheduled(ITrigger trigger)
{
}
public void JobsPaused(string jobGroup)
{
}
public void JobsResumed(string jobGroup)
{
}
public void JobUnscheduled(TriggerKey triggerKey)
{
}
public void SchedulerError(string msg, SchedulerException cause)
{
logger.Error(msg);
var excep = cause as Exception;
while (true)
{
logger.Error(excep.Message);
logger.Error(excep.StackTrace);
excep = excep.InnerException;
}
}
public void SchedulerInStandbyMode()
{
}
public void SchedulerShutdown()
{
logger.Debug($"SchedulerShutdown");
}
public void SchedulerShuttingdown()
{
}
public void SchedulerStarted()
{
logger.Debug($"SchedulerStarted");
}
public void SchedulerStarting()
{
}
public void SchedulingDataCleared()
{
}
public void TriggerFinalized(ITrigger trigger)
{
}
public void TriggerPaused(TriggerKey triggerKey)
{
}
public void TriggerResumed(TriggerKey triggerKey)
{
}
public void TriggersPaused(string triggerGroup)
{
}
public void TriggersResumed(string triggerGroup)
{
}
}
}

@ -0,0 +1,57 @@
using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;
namespace D7DJYMQ
{
class Program
{
private static ILog logger = LogManager.GetLogger("DS7Date");
static void Main(string[] args)
{
var serviceName = ConfigurationManager.AppSettings["ServiceName"];
var serviceDisplayName = ConfigurationManager.AppSettings["ServiceDisplayName"];
if (Environment.UserInteractive)
{
Console.Title = serviceDisplayName;
}
Host host = HostFactory.New(x =>
{
// 基本的配置
x.RunAsLocalSystem();
x.SetServiceName(serviceName);
x.SetDisplayName(serviceDisplayName);
x.StartAutomaticallyDelayed();
x.EnableShutdown();
logger.Debug($"启动接收大简云数据接收服务");
// 注册服务
x.Service(hostSettings => new DS7Date());
logger.Debug($"注册服务");
// 设置服务失败后的操作,分别对应第一次、第二次、后续
x.EnableServiceRecovery(t =>
{
logger.Debug($"注册服失败");
t.RestartService(0);
t.RestartService(0);
t.RestartService(0);
t.OnCrashOnly();
//t.SetResetPeriod(1);
});
});
host.Run();
}
}
}

@ -0,0 +1,37 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("DSWeb.Service.Output.DS7")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DSWeb.Service.Output.DS7")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("324de2ce-c592-4a91-8b40-856652e0d0f0")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" requirePermission="false" />
</configSections>
<log4net>
<root>
<!-- Value of priority may be ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF -->
<level value="DEBUG" />
<appender-ref ref="DebugAppender" />
<appender-ref ref="ErrorAppender" />
</root>
<appender name="DebugAppender" type="log4net.Appender.RollingFileAppender">
<!-- debug log: 记录 DEBUG, INFO 级别的日志 -->
<file value="App_Data\\Logs\\debug.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="100" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout" >
<param name="ConversionPattern" value="%date [%p] [%logger] [%thread] - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMax value="INFO" />
</filter>
</appender>
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<!-- error log: 记录 WARN,ERROR,FATAL 级别的日志 -->
<file value="App_Data\\Logs\\error.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout" >
<param name="ConversionPattern" value="%date [%p] [%logger] [%thread] - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="WARN" />
</filter>
</appender>
</log4net>
</configuration>

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Common.Logging" version="3.3.1" targetFramework="net472" />
<package id="Common.Logging.Core" version="3.3.1" targetFramework="net472" />
<package id="EntityFramework" version="6.4.4" targetFramework="net472" />
<package id="FluentFTP" version="34.0.0" targetFramework="net472" />
<package id="log4net" version="1.2.10" targetFramework="net472" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net472" />
<package id="Quartz" version="2.6.2" targetFramework="net472" />
<package id="RabbitMQ.Client" version="6.2.2" targetFramework="net472" />
<package id="SharpZipLib" version="1.4.2" targetFramework="net472" />
<package id="System.Buffers" version="4.5.1" targetFramework="net472" />
<package id="System.Memory" version="4.5.5" targetFramework="net472" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net472" />
<package id="System.Runtime.CompilerServices.Unsafe" version="4.5.3" targetFramework="net472" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net472" />
<package id="System.Threading.Channels" version="4.7.1" targetFramework="net472" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net472" />
<package id="Topshelf" version="4.3.0" targetFramework="net472" />
</packages>

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8" ?>
<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData">
<processing-directives>
<overwrite-existing-data>true</overwrite-existing-data>
</processing-directives>
<schedule>
<!--
<job>
<name>JobDS7BillOutput</name>
<group>System</group>
<description>账单中心数据导出到东胜7任务</description>
<job-type>DSWeb.BillCenter.Service.DS7.JobDS7BillOutput,DSWeb.BillCenter.Service.DS7</job-type>
<durable>true</durable>
<recover>false</recover>
</job>
<trigger>
<simple>
<name>TriggerDS7BillOutput</name>
<group>System</group>
<description>账单中心数据导出到东胜7任务触发器</description>
<job-name>JobDS7BillOutput</job-name>
<job-group>System</job-group>
<repeat-count>-1</repeat-count>
<repeat-interval>60000</repeat-interval>
</simple>
</trigger>
-->
<!--
<job>
<name>JobDingTalkUserList</name>
<group>System</group>
<description>定时同步钉钉通讯录服务</description>
<job-type>DSWeb.BillCenter.Service.DingtalkUserList.JobDS7BillOutput,DSWeb.BillCenter.Service.DingtalkUserList</job-type>
<durable>true</durable>
<recover>false</recover>
</job>-->
<!--<trigger>
<simple>
<name>TriggerDingTalkUserList</name>
<group>System</group>
<description>定时同步钉钉通讯录服务触发器</description>
<job-name>JobDingTalkUserList</job-name>
<job-group>System</job-group>
<repeat-count>-1</repeat-count>
<repeat-interval>60000</repeat-interval>
</simple>
</trigger>-->
<!--<trigger>
<cron>
<name>TriggerDingTalkUserList</name>
<group>System</group>
<description>定时同步钉钉通讯录服务触发器</description>
<job-name>JobDingTalkUserList</job-name>
<job-group>System</job-group>
<cron-expression>0 0 0/1 * * ? </cron-expression>
</cron>
</trigger>-->
</schedule>
</job-scheduling-data>

@ -0,0 +1,3 @@
1从大简云的公开消息队列获取自己的业务写入ds7经汉版的op_other表作为舱单业务的数据
2定时读取钉钉通讯录

@ -0,0 +1,313 @@
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Topshelf;
namespace DSWeb.Service.Output.DS7
{
public class DS7Date : ServiceControl
{
private static string MQURL = ConfigurationManager.AppSettings["DJYMQURL"];
private static string connStr = ConfigurationManager.AppSettings["ConnectionString"];
private static string virtualhost = ConfigurationManager.AppSettings["virtualhost"];
private static string ExchangeName = ConfigurationManager.AppSettings["MQExchangeName"];
private static string QueueName = ConfigurationManager.AppSettings["MQQueueName"];
private static string MAILSENDACCOUNT = ConfigurationManager.AppSettings["MAILSENDACCOUNT"];
private static string MAILSENDPASSWORD = ConfigurationManager.AppSettings["MAILSENDPASSWORD"];
private static string MAILSENDSERVICE = ConfigurationManager.AppSettings["MAILSENDSERVICE"];
private static string MAILSENDPORT = ConfigurationManager.AppSettings["MAILSENDPORT"];
private static string MAILISSSL = ConfigurationManager.AppSettings["MAILISSSL"];
private static string MAILTITLE = ConfigurationManager.AppSettings["MAILTITLE"];
private static string BSSQL = ConfigurationManager.AppSettings["BSSQL"];
private static IConnection mqConn;
private static ILog logger = LogManager.GetLogger("DS7Date");
public bool Start(HostControl hostControl)
{
logger.Debug($"启动接收大简云订舱数据回推");
var CompanyQueueName = QueueName;
ConnectionFactory factory = new ConnectionFactory();
factory.Uri = new Uri(MQURL);
//factory.UserName = "xgs_test";
//factory.Password = "xgs_test123";
factory.VirtualHost = virtualhost;
mqConn = factory.CreateConnection();
IModel model = mqConn.CreateModel();
model.ExchangeDeclare(ExchangeName, ExchangeType.Direct);
model.QueueDeclare(CompanyQueueName, false, false, false, null);
model.QueueBind(CompanyQueueName, ExchangeName, QueueName);
var consumer = new EventingBasicConsumer(model);
consumer.Received += (ch, ea) =>
{
var body = ea.Body;
var strBody = Encoding.UTF8.GetString(body.ToArray());
logger.Debug($"收到简云截单日期数据回推消息:{strBody}");
try
{
//回写数据
var dateback = JsonConvert.DeserializeAnonymousType(strBody, new { vessel = string.Empty, voyage = string.Empty, ship_agency = string.Empty, cut_off_time = string.Empty, etd = string.Empty });
if (!string.IsNullOrEmpty(dateback.vessel) && !string.IsNullOrEmpty(dateback.voyage) && !string.IsNullOrEmpty(dateback.ship_agency) && !string.IsNullOrEmpty(dateback.cut_off_time))
{
using (SqlConnection dbcon = new SqlConnection(connStr))
{
dbcon.Open();
string maildescrption = "";
var FORWARDER = GetCustEdi(dbcon, dateback.ship_agency);
var SendMailList = new List<SendMail>();
if (!string.IsNullOrEmpty(FORWARDER))
{
var opseaelist = GetBs(dbcon, "VESSEL='" + dateback.vessel + "' AND VOYNO='" + dateback.voyage + "' and FORWARDER='" + FORWARDER + "'");
if (opseaelist != null && opseaelist.Count != 0)
{
var opemail = "";
foreach (var opseae in opseaelist)
{
var tastStr = $" update op_seae set CLOSEDOCDATE='{dateback.cut_off_time}' where BSNO='{opseae.BSNO}' ";
SqlCommand cmdtast = new SqlCommand(tastStr, dbcon);
cmdtast.ExecuteNonQuery();
logger.Debug($"已更新截单日期{dateback.cut_off_time},{opseae.MBLNO},{opseae.BSNO}");
var sendmail = SendMailList.Find(x => x.OP == opseae.OP);
if (sendmail != null)
{
sendmail.MAILDESCRIPTION = sendmail.MAILDESCRIPTION + Environment.NewLine + opseae.MBLNO;
}
else
{
var newsendmail = new SendMail();
newsendmail.OP = opseae.OP;
newsendmail.MAIL = opseae.MAIL;
newsendmail.MAILDESCRIPTION = opseae.MBLNO;
SendMailList.Add(newsendmail);
}
}
}
}
else
{
logger.Debug($"{dateback.ship_agency}没有找到对应的订舱代理");
}
if (SendMailList != null && SendMailList.Count != 0)
{
foreach (var SendMail in SendMailList)
{
SendEmail se = new SendEmail(SendMail.MAIL, MAILSENDACCOUNT, "", "", "截港日期自动更新", SendMail.MAILDESCRIPTION, false);
se.SetSmtp(MAILSENDACCOUNT, MAILSENDPASSWORD, MAILSENDSERVICE, Convert.ToInt16(MAILSENDPORT), false, System.Net.Mail.MailPriority.Normal); //必须在所有参数设置完后调用此方法
logger.Debug($"已给操作{SendMail.OP}发送邮件{SendMail.MAIL}{SendMail.MAILDESCRIPTION}");
}
}
}
}
}
catch (Exception ex)
{
logger.Error($"处理简云订舱数据回推时出错:" + ex.Message);
logger.Error(ex.Message);
logger.Error(ex.StackTrace);
}
};
model.BasicConsume(CompanyQueueName, true, consumer);
//var task = Task.Run(() =>
//{
// while (true)
// {
// var result = model.BasicGet(queue: CompanyQueueName, autoAck: true);
// if (result == null) { Thread.Sleep(10); continue; };
// var strBody = Encoding.UTF8.GetString(result.Body.ToArray());
// logger.Debug($"收到简云截单日期数据回推消息:{strBody}");
// try
// {
// //回写数据
// var dateback = JsonConvert.DeserializeAnonymousType(strBody, new { vessel = string.Empty, voyage = string.Empty, ship_agency = string.Empty, cut_off_time = string.Empty, etd = string.Empty });
// if (!string.IsNullOrEmpty(dateback.vessel) && !string.IsNullOrEmpty(dateback.voyage) && !string.IsNullOrEmpty(dateback.ship_agency) && !string.IsNullOrEmpty(dateback.cut_off_time))
// {
// using (SqlConnection dbcon = new SqlConnection(connStr))
// {
// dbcon.Open();
// string maildescrption = "";
// var FORWARDER = GetCustEdi(dbcon, dateback.ship_agency);
// var SendMailList = new List<SendMail>();
// if (!string.IsNullOrEmpty(FORWARDER))
// {
// var opseaelist = GetBs(dbcon, "VESSEL='" + dateback.vessel + "' AND VOYNO='" + dateback.voyage + "' and FORWARDER='" + FORWARDER + "'" + BSSQL);
// if (opseaelist != null && opseaelist.Count != 0)
// {
// var opemail = "";
// foreach (var opseae in opseaelist)
// {
// var tastStr = $" update op_seae set CLOSEDOCDATE='{dateback.cut_off_time}' where BSNO='{opseae.BSNO}' ";
// SqlCommand cmdtast = new SqlCommand(tastStr, dbcon);
// cmdtast.ExecuteNonQuery();
// logger.Debug($"已更新截单日期{dateback.cut_off_time},{opseae.MBLNO},{opseae.BSNO}");
// var sendmail = SendMailList.Find(x => x.OP == opseae.OP);
// if (sendmail != null)
// {
// sendmail.MAILDESCRIPTION = sendmail.MAILDESCRIPTION + Environment.NewLine + opseae.MBLNO;
// }
// else
// {
// var newsendmail = new SendMail();
// newsendmail.OP = opseae.OP;
// newsendmail.MAIL = opseae.MAIL;
// newsendmail.MAILDESCRIPTION = opseae.MBLNO;
// SendMailList.Add(newsendmail);
// }
// }
// }
// }
// else
// {
// logger.Debug($"{dateback.ship_agency}没有找到对应的订舱代理");
// }
// if (SendMailList != null && SendMailList.Count != 0)
// {
// foreach (var SendMail in SendMailList)
// {
// SendEmail se = new SendEmail(SendMail.MAIL, MAILSENDACCOUNT, "", "", "截港日期自动更新", SendMail.MAILDESCRIPTION, false);
// se.SetSmtp(MAILSENDACCOUNT, MAILSENDPASSWORD, MAILSENDSERVICE, Convert.ToInt16(MAILSENDPORT), false, System.Net.Mail.MailPriority.Normal); //必须在所有参数设置完后调用此方法
// logger.Debug($"已给操作{SendMail.OP}发送邮件{SendMail.MAIL}{SendMail.MAILDESCRIPTION}");
// }
// }
// }
// }
// }
// catch (Exception ex)
// {
// logger.Error($"处理简云订舱数据回推时出错:" + ex.Message);
// logger.Error(ex.Message);
// logger.Error(ex.StackTrace);
// }
// //model.BasicConsume(CompanyQueueName, true, consumer);
// //Console.WriteLine(msg);
// }
//});
//task.Wait();
//model.Close();
//mqConn.Close();
return true;
}
public bool Stop(HostControl hostControl)
{
// 结束
logger.Debug("停止运行");
//StdSchedulerFactory.GetDefaultScheduler().Shutdown();
if (mqConn != null && mqConn.IsOpen)
{
mqConn.Close();
mqConn = null;
}
return true;
}
public class MsOpSeae
{
public string BSNO { get; set; }
public string MBLNO { get; set; }
public string OP { get; set; }
public string MAIL { get; set; }
}
public class SendMail
{
public string OP { get; set; }
public string MAIL { get; set; }
public string MAILDESCRIPTION { get; set; }
}
static public List<MsOpSeae> GetBs(SqlConnection dbcon, string constr)
{
var opseaeList = new List<MsOpSeae>();
var strSql = new StringBuilder();
strSql.Append("select BSNO,MBLNO,OP,FORWARDER,(SELECT TOP 1 EMAIL1 FROM VW_user WHERE SHOWNAME=op_seae.OP) EMAIL from op_seae where " + constr);
strSql.Append(" ORDER BY OP ");
SqlDataAdapter adapter = new SqlDataAdapter(strSql.ToString(), dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
var opseae = new MsOpSeae();
opseae.BSNO = Convert.ToString(row["BSNO"].ToString());
opseae.MBLNO = Convert.ToString(row["MBLNO"].ToString());
opseae.OP = Convert.ToString(row["OP"].ToString());
opseae.MAIL = Convert.ToString(row["EMAIL"].ToString());
opseaeList.Add(opseae);
}
}
return opseaeList;
}
static public string GetCustEdi(SqlConnection dbcon, string constr)
{
string result = "";
var strSql = new StringBuilder();
strSql.Append("select CUST from code_cust_edi where EDINAME='DJY' AND EDICODE='" + constr + "'");
SqlDataAdapter adapter = new SqlDataAdapter(strSql.ToString(), dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
result = Convert.ToString(row["CUST"].ToString());
}
}
return result;
}
}
}

@ -0,0 +1,359 @@
using System;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Globalization;
using System.Linq;
namespace DSWeb.Service.Output.DS7
{
/// <summary>
/// 邮件发送类
/// </summary>
public class SendEmail
{
private MailMessage mailMessage = new MailMessage(); //实例化一个邮件类
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="toAddresses">收件人地址(多个以,号分开)</param>
/// <param name="fromAddress">发件人地址</param>
/// <param name="title">主题</param>
/// <param name="body">正文</param>
public SendEmail(string toAddresses, string fromAddress, string title, string body)
: this(toAddresses, fromAddress, "", "", title, body, false)
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="toAddress">收件人地址</param>
/// <param name="fromAddress">发件人地址</param>
/// <param name="toName">收件人名字</param>
/// <param name="fromName">发件人姓名</param>
/// <param name="title">主题</param>
/// <param name="body">正文</param>
/// <param name="isBodyHtml">正文是否为html格式</param>
public SendEmail(string toAddress, string fromAddress, string toName, string fromName, string title, string body, bool isBodyHtml)
{
mailMessage.From = new MailAddress(fromAddress, fromName, Encoding.GetEncoding(936));
if (toName.Equals(""))
mailMessage.To.Add(toAddress);
else
mailMessage.To.Add(new MailAddress(toAddress, toName, Encoding.GetEncoding(936)));
mailMessage.Subject = title;
mailMessage.SubjectEncoding = Encoding.GetEncoding(936);
mailMessage.Body = body;
mailMessage.IsBodyHtml = isBodyHtml;
mailMessage.BodyEncoding = Encoding.GetEncoding(936);
}
#endregion
/// <summary>
/// 设置SMTP并且将邮件发送出去
/// 所有参数都设置完成后再调用该方法
/// </summary>
/// <param name="password">发件人密码</param>
/// <param name="smtpHost">SMTP服务器地址</param>
public void SetSmtp(string password, string smtpHost)
{
SetSmtp(mailMessage.From.Address, password, smtpHost, 25, false, MailPriority.Normal);
}
/// <summary>
/// 设置SMTP并且将邮件发送出去
/// 所有参数都设置完成后再调用该方法
/// </summary>
/// <param name="address">发件人地址必须为真实有效的email地址</param>
/// <param name="password">发件人密码</param>
/// <param name="smtpHost">SMTP服务器地址</param>
/// <param name="smtpPort">SMTP服务器的端口</param>
/// <param name="isEnableSsl">SMTP服务器是否启用SSL加密</param>
/// <param name="priority">邮件的优先级</param>
public void SetSmtp(string address, string password, string smtpHost, int smtpPort, bool isEnableSsl, MailPriority priority)
{
SmtpClient smtp = new SmtpClient(smtpHost,smtpPort);
// smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
// smtp.UseDefaultCredentials = true;
//if (isEnableSsl)
//{
// smtp.UseDefaultCredentials = true;
// System.Net.NetworkCredential nc = new System.Net.NetworkCredential(address, password);
// smtp.Credentials = nc.GetCredential(smtpHost, smtpPort, "NTLM");
//}
//else
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(address, password);
smtp.Credentials = nc;
//smtp.Credentials = new NetworkCredential(address, password);
//smtp.Host = smtpHost;
//smtp.Port = smtpPort;
smtp.EnableSsl = isEnableSsl;
// smtp.UseDefaultCredentials = true;
// mailMessage.Priority = priority;
try
{
smtp.Send(mailMessage); //发送邮件
}
catch (Exception e)
{
smtp.Dispose();
}
finally
{
smtp.Dispose();
}
smtp.Dispose();
}
class Mailinfo {
public SendEmail se { get; set; }
public string address { get; set; }
public string password { get; set; }
public string smtpHost { get; set; }
public int smtpPort { get; set; }
public bool isEnableSsl { get; set; }
public MailPriority priority { get; set; }
public Mailinfo(SendEmail se, string address, string password, string smtpHost, int smtpPort, bool isEnableSsl, MailPriority priority)
{
this.se = se;
this.address = address;
this.password = password;
this.smtpHost = smtpHost;
this.smtpPort = smtpPort;
this.isEnableSsl = isEnableSsl;
this.priority = priority;
}
}
class ThreadMail
{
public void FuncSend(object o)
{
Mailinfo Mailinfo = o as Mailinfo;
Mailinfo.se.SetSmtp(Mailinfo.address, Mailinfo.password, Mailinfo.smtpHost, Mailinfo.smtpPort, Mailinfo.isEnableSsl, Mailinfo.priority);
}
}
public void SetSmtp_thread( string address, string password, string smtpHost, int smtpPort, bool isEnableSsl, MailPriority priority) {
ThreadMail tmail = new ThreadMail();
//有参调用实例方法ParameterizedThreadStart是一个委托input为object,返回值为void
Thread thread1 = new Thread(new ParameterizedThreadStart(tmail.FuncSend));
Mailinfo mi = new Mailinfo(this, address, password, smtpHost, smtpPort, isEnableSsl, priority);
thread1.Start(mi);
}
#region //设置邮件地址
/// <summary>
/// 设置更多收件人
/// </summary>
/// <param name="toAddresses">收件人地址</param>
public void SetMoreToAddress(string toAddresses)
{
mailMessage.To.Add(toAddresses);
}
/// <summary>
/// 设置更多收件人
/// </summary>
/// <param name="toAddresses">收件人地址</param>
/// <param name="toName">收件人名字</param>
public void SetMoreToAddress(string toAddress, string toName)
{
mailMessage.To.Add(new MailAddress(toAddress, toName, Encoding.GetEncoding(936)));
}
/// <summary>
/// 设置抄送者(多个以,号分开)
/// </summary>
/// <param name="ccAddresses">抄送者地址</param>
public void SetCarbonCopyFor(string ccAddresses)
{
mailMessage.CC.Add(ccAddresses);
}
/// <summary>
/// 设置抄送者
/// </summary>
/// <param name="ccAddress">抄送者地址</param>
/// <param name="ccName">抄送者名字</param>
public void SetCarbonCopyFor(string ccAddress, string ccName)
{
mailMessage.Bcc.Add(new MailAddress(ccAddress, ccName, Encoding.GetEncoding(936)));
}
/// <summary>
/// 设置密送者(多个以,号分开)
/// </summary>
/// <param name="bccAddresses">密送者</param>
public void SetBlindCarbonCopyFor(string bccAddresses)
{
mailMessage.Bcc.Add(bccAddresses);
}
/// <summary>
/// 设置密送者
/// </summary>
/// <param name="bccAddress">密送者</param>
/// <param name="bccName">密送者名字</param>
public void SetBlindCarbonCopyFor(string bccAddress, string bccName)
{
mailMessage.Bcc.Add(new MailAddress(bccAddress, bccName, Encoding.GetEncoding(936)));
}
#endregion
#region 添加附件
/// <summary>
/// 添加附件(自动识别文件类型)
/// </summary>
/// <param name="fileName">单个文件的路径</param>
public void Attachments(string fileName)
{
mailMessage.Attachments.Add(new Attachment(fileName));
}
/// <summary>
/// 添加附件默认为富文本RTF格式
/// </summary>
/// <param name="fileName">单个文件的路径</param>
public void AttachmentsForRTF(string fileName)
{
mailMessage.Attachments.Add(new Attachment(fileName, MediaTypeNames.Application.Rtf));
}
//public void SaveToEml(string emlFileAbsolutePath)
//{
// const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
// using (MemoryStream ms = new MemoryStream())
// {
//     Assembly assembly = typeof(System.Net.Mail.SmtpClient).Assembly;
//     Type tMailWriter = assembly.GetType("System.Net.Mail.MailWriter");
//     object mailWriter = Activator.CreateInstance(tMailWriter, flags, null, new object[] { ms }, CultureInfo.InvariantCulture);
// mailMessage.GetType().GetMethod("Send", flags).Invoke(mailMessage, new object[] { mailWriter, true });
//     File.WriteAllText(emlFileAbsolutePath, System.Text.Encoding.Default.GetString(ms.ToArray()), System.Text.Encoding.Default);
// }
//}
public struct MailBillType
{
public const string = "EDI";
public const string VGM = "VGM";
}
public struct MailInfo {
public const string _ = "DSFTP_EDI_FTP_EDIPATH";
public const string VGM_ = "DSFTP_EDI_FTP_VGMPATH";
public const string __ = "申请发送 ";
public const string __ = "舱单发送-";
public const string VGM__ = "申请发送VGM-";
public const string VGM__ = "VGM发送-";
}
public void SaveToEml(string emlFileAbsolutePath, string billtype)
{
var assembly = typeof(SmtpClient).Assembly;
var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
using (var memoryStream = new MemoryStream())
{
// Get reflection info for MailWriter contructor
var mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
// Construct MailWriter object with our FileStream
var mailWriter = mailWriterContructor.Invoke(new object[] { memoryStream });
// Get reflection info for Send() method on MailMessage
var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
//20210622 标题 按GB2312转base64
var mailhead = "";
var ftphead = "";
if(billtype== MailBillType.)
{
mailhead = MailInfo.__;
ftphead = MailInfo.__;
}
if (billtype == MailBillType.VGM)
{
mailhead = MailInfo.VGM__;
ftphead = MailInfo.VGM__;
}
string title = Convert.ToBase64String(System.Text.Encoding.GetEncoding(936).GetBytes(mailMessage.Subject.Replace(mailhead, ftphead)));
var codedtitle= "=?GB2312?B?"+title+"?=";
// Call method passing in MailWriter
sendMethod.Invoke(mailMessage, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
// Finally get reflection info for Close() method on our MailWriter
var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
// Call close method
closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
var _str = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()).Replace(mailMessage.Subject, codedtitle);
File.WriteAllText(emlFileAbsolutePath, _str, System.Text.Encoding.Default);
//return Encoding.ASCII.GetString(memoryStream.ToArray());
}
}
public MailMessage getMailMessage() {
return mailMessage;
}
#endregion
/// <summary>
/// 将MailMessage保存为eml文件
/// </summary>
/// <param name="msg">待保存的具有内容的MailMessage</param>
/// <param name="emlFileAbsolutePath">保存后的eml文件的路径</param>
public void SaveToEml(string emlFileAbsolutePath)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
using (MemoryStream ms = new MemoryStream())
{
Assembly assembly = typeof(System.Net.Mail.SmtpClient).Assembly;
Type tMailWriter = assembly.GetType("System.Net.Mail.MailWriter");
object mailWriter = Activator.CreateInstance(tMailWriter, flags, null, new object[] { ms }, CultureInfo.InvariantCulture);
mailMessage.GetType().GetMethod("Send", flags).Invoke(mailMessage, new object[] { mailWriter, true });
File.WriteAllText(emlFileAbsolutePath, System.Text.Encoding.Default.GetString(ms.ToArray()), System.Text.Encoding.Default);
}
}
}
}

@ -0,0 +1,359 @@
using System;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Globalization;
using System.Linq;
namespace JobSendAgentMail
{
/// <summary>
/// 邮件发送类
/// </summary>
public class SendEmail
{
private MailMessage mailMessage = new MailMessage(); //实例化一个邮件类
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="toAddresses">收件人地址(多个以,号分开)</param>
/// <param name="fromAddress">发件人地址</param>
/// <param name="title">主题</param>
/// <param name="body">正文</param>
public SendEmail(string toAddresses, string fromAddress, string title, string body)
: this(toAddresses, fromAddress, "", "", title, body, false)
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="toAddress">收件人地址</param>
/// <param name="fromAddress">发件人地址</param>
/// <param name="toName">收件人名字</param>
/// <param name="fromName">发件人姓名</param>
/// <param name="title">主题</param>
/// <param name="body">正文</param>
/// <param name="isBodyHtml">正文是否为html格式</param>
public SendEmail(string toAddress, string fromAddress, string toName, string fromName, string title, string body, bool isBodyHtml)
{
mailMessage.From = new MailAddress(fromAddress, fromName, Encoding.GetEncoding(936));
if (toName.Equals(""))
mailMessage.To.Add(toAddress);
else
mailMessage.To.Add(new MailAddress(toAddress, toName, Encoding.GetEncoding(936)));
mailMessage.Subject = title;
mailMessage.SubjectEncoding = Encoding.GetEncoding(936);
mailMessage.Body = body;
mailMessage.IsBodyHtml = isBodyHtml;
mailMessage.BodyEncoding = Encoding.GetEncoding(936);
}
#endregion
/// <summary>
/// 设置SMTP并且将邮件发送出去
/// 所有参数都设置完成后再调用该方法
/// </summary>
/// <param name="password">发件人密码</param>
/// <param name="smtpHost">SMTP服务器地址</param>
public void SetSmtp(string password, string smtpHost)
{
SetSmtp(mailMessage.From.Address, password, smtpHost, 25, false, MailPriority.Normal);
}
/// <summary>
/// 设置SMTP并且将邮件发送出去
/// 所有参数都设置完成后再调用该方法
/// </summary>
/// <param name="address">发件人地址必须为真实有效的email地址</param>
/// <param name="password">发件人密码</param>
/// <param name="smtpHost">SMTP服务器地址</param>
/// <param name="smtpPort">SMTP服务器的端口</param>
/// <param name="isEnableSsl">SMTP服务器是否启用SSL加密</param>
/// <param name="priority">邮件的优先级</param>
public void SetSmtp(string address, string password, string smtpHost, int smtpPort, bool isEnableSsl, MailPriority priority)
{
SmtpClient smtp = new SmtpClient(smtpHost,smtpPort);
// smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
// smtp.UseDefaultCredentials = true;
//if (isEnableSsl)
//{
// smtp.UseDefaultCredentials = true;
// System.Net.NetworkCredential nc = new System.Net.NetworkCredential(address, password);
// smtp.Credentials = nc.GetCredential(smtpHost, smtpPort, "NTLM");
//}
//else
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(address, password);
smtp.Credentials = nc;
//smtp.Credentials = new NetworkCredential(address, password);
//smtp.Host = smtpHost;
//smtp.Port = smtpPort;
smtp.EnableSsl = isEnableSsl;
// smtp.UseDefaultCredentials = true;
// mailMessage.Priority = priority;
try
{
smtp.Send(mailMessage); //发送邮件
}
catch (Exception e)
{
smtp.Dispose();
}
finally
{
smtp.Dispose();
}
smtp.Dispose();
}
class Mailinfo {
public SendEmail se { get; set; }
public string address { get; set; }
public string password { get; set; }
public string smtpHost { get; set; }
public int smtpPort { get; set; }
public bool isEnableSsl { get; set; }
public MailPriority priority { get; set; }
public Mailinfo(SendEmail se, string address, string password, string smtpHost, int smtpPort, bool isEnableSsl, MailPriority priority)
{
this.se = se;
this.address = address;
this.password = password;
this.smtpHost = smtpHost;
this.smtpPort = smtpPort;
this.isEnableSsl = isEnableSsl;
this.priority = priority;
}
}
class ThreadMail
{
public void FuncSend(object o)
{
Mailinfo Mailinfo = o as Mailinfo;
Mailinfo.se.SetSmtp(Mailinfo.address, Mailinfo.password, Mailinfo.smtpHost, Mailinfo.smtpPort, Mailinfo.isEnableSsl, Mailinfo.priority);
}
}
public void SetSmtp_thread( string address, string password, string smtpHost, int smtpPort, bool isEnableSsl, MailPriority priority) {
ThreadMail tmail = new ThreadMail();
//有参调用实例方法ParameterizedThreadStart是一个委托input为object,返回值为void
Thread thread1 = new Thread(new ParameterizedThreadStart(tmail.FuncSend));
Mailinfo mi = new Mailinfo(this, address, password, smtpHost, smtpPort, isEnableSsl, priority);
thread1.Start(mi);
}
#region //设置邮件地址
/// <summary>
/// 设置更多收件人
/// </summary>
/// <param name="toAddresses">收件人地址</param>
public void SetMoreToAddress(string toAddresses)
{
mailMessage.To.Add(toAddresses);
}
/// <summary>
/// 设置更多收件人
/// </summary>
/// <param name="toAddresses">收件人地址</param>
/// <param name="toName">收件人名字</param>
public void SetMoreToAddress(string toAddress, string toName)
{
mailMessage.To.Add(new MailAddress(toAddress, toName, Encoding.GetEncoding(936)));
}
/// <summary>
/// 设置抄送者(多个以,号分开)
/// </summary>
/// <param name="ccAddresses">抄送者地址</param>
public void SetCarbonCopyFor(string ccAddresses)
{
mailMessage.CC.Add(ccAddresses);
}
/// <summary>
/// 设置抄送者
/// </summary>
/// <param name="ccAddress">抄送者地址</param>
/// <param name="ccName">抄送者名字</param>
public void SetCarbonCopyFor(string ccAddress, string ccName)
{
mailMessage.Bcc.Add(new MailAddress(ccAddress, ccName, Encoding.GetEncoding(936)));
}
/// <summary>
/// 设置密送者(多个以,号分开)
/// </summary>
/// <param name="bccAddresses">密送者</param>
public void SetBlindCarbonCopyFor(string bccAddresses)
{
mailMessage.Bcc.Add(bccAddresses);
}
/// <summary>
/// 设置密送者
/// </summary>
/// <param name="bccAddress">密送者</param>
/// <param name="bccName">密送者名字</param>
public void SetBlindCarbonCopyFor(string bccAddress, string bccName)
{
mailMessage.Bcc.Add(new MailAddress(bccAddress, bccName, Encoding.GetEncoding(936)));
}
#endregion
#region 添加附件
/// <summary>
/// 添加附件(自动识别文件类型)
/// </summary>
/// <param name="fileName">单个文件的路径</param>
public void Attachments(string fileName)
{
mailMessage.Attachments.Add(new Attachment(fileName));
}
/// <summary>
/// 添加附件默认为富文本RTF格式
/// </summary>
/// <param name="fileName">单个文件的路径</param>
public void AttachmentsForRTF(string fileName)
{
mailMessage.Attachments.Add(new Attachment(fileName, MediaTypeNames.Application.Rtf));
}
//public void SaveToEml(string emlFileAbsolutePath)
//{
// const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
// using (MemoryStream ms = new MemoryStream())
// {
//     Assembly assembly = typeof(System.Net.Mail.SmtpClient).Assembly;
//     Type tMailWriter = assembly.GetType("System.Net.Mail.MailWriter");
//     object mailWriter = Activator.CreateInstance(tMailWriter, flags, null, new object[] { ms }, CultureInfo.InvariantCulture);
// mailMessage.GetType().GetMethod("Send", flags).Invoke(mailMessage, new object[] { mailWriter, true });
//     File.WriteAllText(emlFileAbsolutePath, System.Text.Encoding.Default.GetString(ms.ToArray()), System.Text.Encoding.Default);
// }
//}
public struct MailBillType
{
public const string = "EDI";
public const string VGM = "VGM";
}
public struct MailInfo {
public const string _ = "DSFTP_EDI_FTP_EDIPATH";
public const string VGM_ = "DSFTP_EDI_FTP_VGMPATH";
public const string __ = "申请发送 ";
public const string __ = "舱单发送-";
public const string VGM__ = "申请发送VGM-";
public const string VGM__ = "VGM发送-";
}
public void SaveToEml(string emlFileAbsolutePath, string billtype)
{
var assembly = typeof(SmtpClient).Assembly;
var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
using (var memoryStream = new MemoryStream())
{
// Get reflection info for MailWriter contructor
var mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
// Construct MailWriter object with our FileStream
var mailWriter = mailWriterContructor.Invoke(new object[] { memoryStream });
// Get reflection info for Send() method on MailMessage
var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
//20210622 标题 按GB2312转base64
var mailhead = "";
var ftphead = "";
if(billtype== MailBillType.)
{
mailhead = MailInfo.__;
ftphead = MailInfo.__;
}
if (billtype == MailBillType.VGM)
{
mailhead = MailInfo.VGM__;
ftphead = MailInfo.VGM__;
}
string title = Convert.ToBase64String(System.Text.Encoding.GetEncoding(936).GetBytes(mailMessage.Subject.Replace(mailhead, ftphead)));
var codedtitle= "=?GB2312?B?"+title+"?=";
// Call method passing in MailWriter
sendMethod.Invoke(mailMessage, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
// Finally get reflection info for Close() method on our MailWriter
var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
// Call close method
closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
var _str = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()).Replace(mailMessage.Subject, codedtitle);
File.WriteAllText(emlFileAbsolutePath, _str, System.Text.Encoding.Default);
//return Encoding.ASCII.GetString(memoryStream.ToArray());
}
}
public MailMessage getMailMessage() {
return mailMessage;
}
#endregion
/// <summary>
/// 将MailMessage保存为eml文件
/// </summary>
/// <param name="msg">待保存的具有内容的MailMessage</param>
/// <param name="emlFileAbsolutePath">保存后的eml文件的路径</param>
public void SaveToEml(string emlFileAbsolutePath)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
using (MemoryStream ms = new MemoryStream())
{
Assembly assembly = typeof(System.Net.Mail.SmtpClient).Assembly;
Type tMailWriter = assembly.GetType("System.Net.Mail.MailWriter");
object mailWriter = Activator.CreateInstance(tMailWriter, flags, null, new object[] { ms }, CultureInfo.InvariantCulture);
mailMessage.GetType().GetMethod("Send", flags).Invoke(mailMessage, new object[] { mailWriter, true });
File.WriteAllText(emlFileAbsolutePath, System.Text.Encoding.Default.GetString(ms.ToArray()), System.Text.Encoding.Default);
}
}
}
}

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A6656568-5C05-4E6C-856B-3FBE6367EA62}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>JobSendAgentMail</RootNamespace>
<AssemblyName>JobSendAgentMail</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Common.Logging, Version=3.3.1.0, Culture=neutral, PublicKeyToken=af08829b84f0328e, processorArchitecture=MSIL">
<HintPath>..\packages\Common.Logging.3.3.1\lib\net40\Common.Logging.dll</HintPath>
</Reference>
<Reference Include="Common.Logging.Core, Version=3.3.1.0, Culture=neutral, PublicKeyToken=af08829b84f0328e, processorArchitecture=MSIL">
<HintPath>..\packages\Common.Logging.Core.3.3.1\lib\net40\Common.Logging.Core.dll</HintPath>
</Reference>
<Reference Include="HtmlAgilityPack">
<HintPath>..\packages\HtmlAgilityPack.1.11.29\lib\Net45\HtmlAgilityPack.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.8\lib\net40-full\log4net.dll</HintPath>
</Reference>
<Reference Include="MailKit, Version=2.9.0.0, Culture=neutral, PublicKeyToken=4e064fe7c44a8f1b, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\MailKit.2.7.0\lib\net45\MailKit.dll</HintPath>
</Reference>
<Reference Include="MimeKit, Version=2.9.0.0, Culture=neutral, PublicKeyToken=bede1c8a46c66814, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\MimeKit.2.8.0\lib\net45\MimeKit.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Quartz, Version=2.6.2.0, Culture=neutral, PublicKeyToken=f6b8c98a402cc8a4, processorArchitecture=MSIL">
<HintPath>..\packages\Quartz.2.6.2\lib\net40\Quartz.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DsSendMail.cs" />
<Compile Include="JobSendCtn.cs" />
<Compile Include="JobSendBooking.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="job_scheduling_data_2_0.xsd">
<SubType>Designer</SubType>
</None>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Content Include="MailTemplate.html" />
<Content Include="quartz_jobs.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<SubType>Designer</SubType>
</Content>
</ItemGroup>
<ItemGroup>
<Folder Include="Model\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.645
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JobSendAgentMail", "JobSendAgentMail.csproj", "{A6656568-5C05-4E6C-856B-3FBE6367EA62}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A6656568-5C05-4E6C-856B-3FBE6367EA62}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A6656568-5C05-4E6C-856B-3FBE6367EA62}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A6656568-5C05-4E6C-856B-3FBE6367EA62}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A6656568-5C05-4E6C-856B-3FBE6367EA62}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F248838F-C29F-4E83-9BE4-082DCE9504F6}
EndGlobalSection
EndGlobal

@ -0,0 +1,218 @@
using log4net;
using Quartz;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using MailKit.Net.Smtp;
using MimeKit;
using HtmlAgilityPack;
namespace JobSendAgentMail
{
public class JobSendBooking : IJob
{
private ILog log = LogManager.GetLogger(typeof(JobSendBooking));
public void Execute(IJobExecutionContext context)
{
string connStr = context.JobDetail.JobDataMap.GetString("ConnectString");
string querySql = context.JobDetail.JobDataMap.GetString("QuerySql");
string hblquerySql = context.JobDetail.JobDataMap.GetString("HblQuerySql");
string DocType = context.JobDetail.JobDataMap.GetString("DocType");
string D7FilePath = context.JobDetail.JobDataMap.GetString("D7FilePath");
string MAILSENDACCOUNT = context.JobDetail.JobDataMap.GetString("MAILSENDACCOUNT");
string MAILSENDPASSWORD = context.JobDetail.JobDataMap.GetString("MAILSENDPASSWORD");
string MAILSENDSERVICE = context.JobDetail.JobDataMap.GetString("MAILSENDSERVICE");
string MAILSENDPORT = context.JobDetail.JobDataMap.GetString("MAILSENDPORT");
string MAILISSSL = context.JobDetail.JobDataMap.GetString("MAILISSSL");
string MAILTEMPLATE = context.JobDetail.JobDataMap.GetString("MAILTEMPLATE");
string MAILTITLEJOB = context.JobDetail.JobDataMap.GetString("MAILTITLE");
log.Debug($"开始执行代理发送邮件");
using (SqlConnection dbcon = new SqlConnection(connStr))
{
SqlDataAdapter adapter = new SqlDataAdapter(querySql, dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Columns.Contains("MBLNO") && table.Columns.Contains("AGENTID"))
{
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
if (row["MBLNO"].ToString() != "" && row["AGENTID"].ToString() != "")
{
var htmlFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, MAILTEMPLATE);
var content = File.ReadAllText(htmlFile);
var REMARKSTR = row["BLREMARK"].ToString();
REMARKSTR = REMARKSTR.Replace("\r\n", "<br />");
REMARKSTR = REMARKSTR.Replace("\n", "<br />");
REMARKSTR = REMARKSTR.Replace("\r", "");
content = content.Replace("$MBLNO$", row["MBLNO"].ToString());
content = content.Replace("$ETD$", row["ETD"].ToString());
content = content.Replace("$BLFRT$", row["BLFRT"].ToString());
content = content.Replace("$PORTLOAD$", row["PORTLOAD"].ToString());
content = content.Replace("$PORTDISCHARGE$", row["PORTDISCHARGE"].ToString());
content = content.Replace("$DESTINATION$", row["DESTINATION"].ToString());
content = content.Replace("$ATD$", row["ATD"].ToString());
content = content.Replace("$HBLNO$", row["HBLNO"].ToString());
content = content.Replace("$ORDERNO$", row["ORDERNO"].ToString());
content = content.Replace("$ETA$", row["ETA"].ToString());
content = content.Replace("$CNTRTOTAL$", row["CNTRTOTAL"].ToString());
content = content.Replace("$CARRIERID$", row["CARRIERID"].ToString());
content = content.Replace("$ISSUETYPE$", row["ISSUETYPE"].ToString());
content = content.Replace("$BLREMARK$", REMARKSTR);
var MAILTITLE = MAILTITLEJOB;
MAILTITLE = MAILTITLE.Replace("$MBLNO$", row["MBLNO"].ToString());
MAILTITLE = MAILTITLE.Replace("$ETD$", row["ETD"].ToString());
MAILTITLE = MAILTITLE.Replace("$BLFRT$", row["BLFRT"].ToString());
MAILTITLE = MAILTITLE.Replace("$PORTLOAD$", row["PORTLOAD"].ToString());
MAILTITLE = MAILTITLE.Replace("$PORTDISCHARGE$", row["PORTDISCHARGE"].ToString());
MAILTITLE = MAILTITLE.Replace("$DESTINATION$", row["DESTINATION"].ToString());
MAILTITLE = MAILTITLE.Replace("$ATD$", row["ATD"].ToString());
MAILTITLE = MAILTITLE.Replace("$HBLNO$", row["HBLNO"].ToString());
MAILTITLE = MAILTITLE.Replace("$ORDERNO$", row["ORDERNO"].ToString());
MAILTITLE = MAILTITLE.Replace("$ETA$", row["ETA"].ToString());
MAILTITLE = MAILTITLE.Replace("$CNTRTOTAL$", row["CNTRTOTAL"].ToString());
MAILTITLE = MAILTITLE.Replace("$CARRIERID$", row["CARRIERID"].ToString());
MAILTITLE = MAILTITLE.Replace("$ISSUETYPE$", row["ISSUETYPE"].ToString());
MAILTITLE = MAILTITLE.Replace("$BLREMARK$", row["BLREMARK"].ToString());
SqlDataAdapter hbladapter = new SqlDataAdapter(hblquerySql + " where BSNO='" + row["BSNO"].ToString() + "'", dbcon);
DataTable hbltable = new DataTable();
hbladapter.Fill(hbltable);
var hblstr = "";
if (hbltable.Rows.Count > 0)
{
foreach (DataRow hblrow in hbltable.Rows)
{
hblstr = hblstr + "HB/L:" + hblrow["HBLNO"].ToString() + "-" + hblrow["ISSUETYPE"].ToString() + ":hold<br />";
}
}
content = content.Replace("$HBLCONTENT$", hblstr);
StringWriter writer = new StringWriter();
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(content);
htmlDoc.Save(writer);
string str = writer.ToString();
try
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(row["OPNAME"].ToString(), row["OPEMAIL"].ToString()));
var maillist = row["AGENTEMAIL"].ToString().Split(';');
foreach (var mailaddr in maillist)
{
message.To.Add(MailboxAddress.Parse(mailaddr));
}
message.To.Add(MailboxAddress.Parse(row["OPEMAIL"].ToString()));
// message.Subject = "Pre-alert/" + row["ORDERNO"].ToString() + "/" + row["HBLNO"].ToString();
message.Subject = MAILTITLE;
var html = new TextPart("html")
{
Text = str
};
MimeEntity entity = html;
//SendEmail se = new SendEmail(row["AGENTEMAIL"].ToString(), row["OPEMAIL"].ToString(), "", row["OPNAME"].ToString(), "Pre-alert/" + row["ORDERNO"].ToString() + "/" + row["HBLNO"].ToString(), str,true);
SqlDataAdapter fileadapter = new SqlDataAdapter("SELECT * FROM Receipt_Doc where RECEIPTTYPE='" + DocType + "' and BSNO='" + row["BSNO"].ToString() + "'", dbcon);
DataTable filetable = new DataTable();
fileadapter.Fill(filetable);
if (filetable.Rows.Count > 0)
{
var mult = new Multipart("mixed") { html };
foreach (DataRow filerow in filetable.Rows)
{
var attfile = filerow["Driect_URL"].ToString();
if (!string.IsNullOrEmpty(attfile))
{
attfile = attfile.Replace("../../", D7FilePath);
while ((attfile.IndexOf("/") >= 0))
{
attfile = attfile.Replace("/", @"\");
}
if (File.Exists(attfile))
{
var tmpDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "temp");
if (!Directory.Exists(tmpDir))
{
Directory.CreateDirectory(tmpDir);
}
var tmpFile = Path.Combine(tmpDir, filerow["URL"].ToString());
File.Copy(attfile, tmpFile, true);
var attPart = new MimePart();
attPart.Content = new MimeContent(new FileStream(attfile, FileMode.Open));
attPart.ContentDisposition = new ContentDisposition(ContentDisposition.Attachment);
attPart.FileName = filerow["URL"].ToString();
mult.Add(attPart);
//se.Attachments(attfile);
}
else
{
log.Debug($"附件文件:{attfile}不存在");
// logger.Error($"邮件{sendMail.GID}的附件文件{att.FilePath}不存在");
}
}
}
entity = mult;
}
//se.SetSmtp(MAILSENDACCOUNT, MAILSENDPASSWORD, MAILSENDSERVICE, Convert.ToInt16(MAILSENDPORT), Convert.ToBoolean(MAILISSSL), System.Net.Mail.MailPriority.Normal); //必须在所有参数设置完后调用此方法
message.Body = entity;
using (var client = new SmtpClient())
{
client.Connect(MAILSENDSERVICE, Convert.ToInt16(MAILSENDPORT), Convert.ToBoolean(MAILISSSL));
client.Authenticate(MAILSENDACCOUNT, MAILSENDPASSWORD);
client.Send(message);
client.Disconnect(true);
}
log.Debug($"邮件发送成功");
}
catch (Exception ex)
{
log.Debug($"邮件发送失败:错误信息{ex.Message}");
}
}
else {
log.Debug($"资料不全:{row["BSNO"].ToString()}");
}
}
}
else
{
log.Debug($"未查询到数据SQL语句{querySql}");
}
}
else
{
log.Error($"未包含所需的列(mblno,carrierid,portloadid)SQL语句{querySql}");
}
}
}
}
}

@ -0,0 +1,116 @@
using log4net;
using Quartz;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using MailKit.Net.Smtp;
using MimeKit;
using HtmlAgilityPack;
namespace JobSendAgentMail
{
public class JobSendCtn : IJob
{
private ILog log = LogManager.GetLogger(typeof(JobSendCtn));
public void Execute(IJobExecutionContext context)
{
string connStr = context.JobDetail.JobDataMap.GetString("ConnectString");
string querySql = context.JobDetail.JobDataMap.GetString("QuerySql");
string MAILSENDACCOUNT = context.JobDetail.JobDataMap.GetString("MAILSENDACCOUNT");
string MAILSENDPASSWORD = context.JobDetail.JobDataMap.GetString("MAILSENDPASSWORD");
string MAILSENDSERVICE = context.JobDetail.JobDataMap.GetString("MAILSENDSERVICE");
string MAILSENDPORT = context.JobDetail.JobDataMap.GetString("MAILSENDPORT");
string MAILISSSL = context.JobDetail.JobDataMap.GetString("MAILISSSL");
//string MAILTEMPLATE = context.JobDetail.JobDataMap.GetString("MAILTEMPLATE");
string MAILTITLEJOB = context.JobDetail.JobDataMap.GetString("MAILTITLE");
string receiver = context.JobDetail.JobDataMap.GetString("MAILRECEIVER");
log.Debug($"开始执行发送邮件");
string maildescrption = "";
using (SqlConnection dbcon = new SqlConnection(connStr))
{
SqlDataAdapter adapter = new SqlDataAdapter(querySql, dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Columns.Contains("箱号"))
{
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
if (row["箱号"].ToString() != "")
{
maildescrption = maildescrption + Environment.NewLine + row["箱号"].ToString();
}
else {
log.Debug($"资料不全:{row["BSNO"].ToString()}");
}
}
}
else
{
log.Debug($"未查询到数据SQL语句{querySql}");
}
if (!string.IsNullOrEmpty(maildescrption)) {
try
{
SendEmail se = new SendEmail(receiver, MAILSENDACCOUNT, "", "", MAILTITLEJOB, maildescrption, false);
se.SetSmtp(MAILSENDACCOUNT, MAILSENDPASSWORD, MAILSENDSERVICE,Convert.ToInt16(MAILSENDPORT), false, System.Net.Mail.MailPriority.Normal); //必须在所有参数设置完后调用此方法
//var message = new MimeMessage();
//message.From.Add(new MailboxAddress(MAILSENDACCOUNT, MAILSENDACCOUNT));
//var maillist = receiver.Split(';');
//foreach (var mailaddr in maillist)
//{
// message.To.Add(MailboxAddress.Parse(mailaddr));
//}
//message.Subject = MAILTITLEJOB;
//var bodyBuilder = new BodyBuilder();
//bodyBuilder.TextBody = maildescrption;
//message.Body = bodyBuilder.ToMessageBody();
//using (var client = new SmtpClient())
//{
// client.Connect(MAILSENDSERVICE, Convert.ToInt16(MAILSENDPORT),false);
// client.Authenticate(MAILSENDACCOUNT, MAILSENDPASSWORD);
// client.Send(message);
// client.Disconnect(true);
//}
log.Debug($"邮件发送成功");
}
catch (Exception ex)
{
log.Debug($"邮件发送失败:错误信息{ex.Message}");
}
}
}
else
{
log.Error($"未包含所需的列(mblno,carrierid,portloadid)SQL语句{querySql}");
}
}
}
}
}

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html>
<p>
<h1 style="text-align:center;">
pre-alert
</h1>
Dear
Customer:<br />
Pls refer pre-alert as
below:<br />
S/S:$CARRIERID$<br />
VOL:$CNTRTOTAL$ <br />
POL:$PORTLOAD$<br />
POD:$PORTDISCHARGE$<br />
DEST:$DESTINATION$<br />
ATD:$ATD$<br />
ETA:$ETA$<br />
MB/L:$MBLNO$-$ISSUETYPE$:hold<br />
$HBLCONTENT$
Importance:<br />
Please <span style="background-color:yellow;">hold the subject shipment </span>till
further notice from Perways.<br />
MUST release the shipment against Telex
Release HB/L from consignee and releasing notice from
Perways.<br />
If you have any questions, pls let us know.
Thanks.
</p>
<p>
<br />
</p>
</html>

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JobYunDang")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("JobYunDang")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("a76c1698-c924-44fa-8a64-51329927d7e0")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,364 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://quartznet.sourceforge.net/JobSchedulingData"
targetNamespace="http://quartznet.sourceforge.net/JobSchedulingData"
elementFormDefault="qualified"
version="2.0">
<xs:element name="job-scheduling-data">
<xs:annotation>
<xs:documentation>Root level node</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element name="pre-processing-commands" type="pre-processing-commandsType" minOccurs="0" maxOccurs="1">
<xs:annotation>
<xs:documentation>Commands to be executed before scheduling the jobs and triggers in this file.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="processing-directives" type="processing-directivesType" minOccurs="0" maxOccurs="1">
<xs:annotation>
<xs:documentation>Directives to be followed while scheduling the jobs and triggers in this file.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="schedule" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element name="job" type="job-detailType" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="trigger" type="triggerType" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="version" type="xs:string">
<xs:annotation>
<xs:documentation>Version of the XML Schema instance</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:complexType name="pre-processing-commandsType">
<xs:sequence maxOccurs="unbounded">
<xs:element name="delete-jobs-in-group" type="xs:string" minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:documentation>Delete all jobs, if any, in the identified group. "*" can be used to identify all groups. Will also result in deleting all triggers related to the jobs.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="delete-triggers-in-group" type="xs:string" minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:documentation>Delete all triggers, if any, in the identified group. "*" can be used to identify all groups. Will also result in deletion of related jobs that are non-durable.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="delete-job" minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:documentation>Delete the identified job if it exists (will also result in deleting all triggers related to it).</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="group" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="delete-trigger" minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:documentation>Delete the identified trigger if it exists (will also result in deletion of related jobs that are non-durable).</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="group" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="processing-directivesType">
<xs:sequence>
<xs:element name="overwrite-existing-data" type="xs:boolean" minOccurs="0" default="true">
<xs:annotation>
<xs:documentation>Whether the existing scheduling data (with same identifiers) will be overwritten. If false, and ignore-duplicates is not false, and jobs or triggers with the same names already exist as those in the file, an error will occur.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="ignore-duplicates" type="xs:boolean" minOccurs="0" default="false">
<xs:annotation>
<xs:documentation>If true (and overwrite-existing-data is false) then any job/triggers encountered in this file that have names that already exist in the scheduler will be ignored, and no error will be produced.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="schedule-trigger-relative-to-replaced-trigger" type="xs:boolean" minOccurs="0" default="false">
<xs:annotation>
<xs:documentation>If true trigger's start time is calculated based on earlier run time instead of fixed value. Trigger's start time must be undefined for this to work.</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="job-detailType">
<xs:annotation>
<xs:documentation>Define a JobDetail</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="group" type="xs:string" minOccurs="0" />
<xs:element name="description" type="xs:string" minOccurs="0" />
<xs:element name="job-type" type="xs:string" />
<xs:sequence minOccurs="0">
<xs:element name="durable" type="xs:boolean" />
<xs:element name="recover" type="xs:boolean" />
</xs:sequence>
<xs:element name="job-data-map" type="job-data-mapType" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="job-data-mapType">
<xs:annotation>
<xs:documentation>Define a JobDataMap</xs:documentation>
</xs:annotation>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="entry" type="entryType" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="entryType">
<xs:annotation>
<xs:documentation>Define a JobDataMap entry</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element name="key" type="xs:string" />
<xs:element name="value" type="xs:string" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="triggerType">
<xs:annotation>
<xs:documentation>Define a Trigger</xs:documentation>
</xs:annotation>
<xs:choice>
<xs:element name="simple" type="simpleTriggerType" />
<xs:element name="cron" type="cronTriggerType" />
<xs:element name="calendar-interval" type="calendarIntervalTriggerType" />
</xs:choice>
</xs:complexType>
<xs:complexType name="abstractTriggerType" abstract="true">
<xs:annotation>
<xs:documentation>Common Trigger definitions</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="group" type="xs:string" minOccurs="0" />
<xs:element name="description" type="xs:string" minOccurs="0" />
<xs:element name="job-name" type="xs:string" />
<xs:element name="job-group" type="xs:string" minOccurs="0" />
<xs:element name="priority" type="xs:nonNegativeInteger" minOccurs="0" />
<xs:element name="calendar-name" type="xs:string" minOccurs="0" />
<xs:element name="job-data-map" type="job-data-mapType" minOccurs="0" />
<xs:sequence minOccurs="0">
<xs:choice>
<xs:element name="start-time" type="xs:dateTime" />
<xs:element name="start-time-seconds-in-future" type="xs:nonNegativeInteger" />
</xs:choice>
<xs:element name="end-time" type="xs:dateTime" minOccurs="0" />
</xs:sequence>
</xs:sequence>
</xs:complexType>
<xs:complexType name="simpleTriggerType">
<xs:annotation>
<xs:documentation>Define a SimpleTrigger</xs:documentation>
</xs:annotation>
<xs:complexContent>
<xs:extension base="abstractTriggerType">
<xs:sequence>
<xs:element name="misfire-instruction" type="simple-trigger-misfire-instructionType" minOccurs="0" />
<xs:sequence minOccurs="0">
<xs:element name="repeat-count" type="repeat-countType" />
<xs:element name="repeat-interval" type="xs:nonNegativeInteger" />
</xs:sequence>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="cronTriggerType">
<xs:annotation>
<xs:documentation>Define a CronTrigger</xs:documentation>
</xs:annotation>
<xs:complexContent>
<xs:extension base="abstractTriggerType">
<xs:sequence>
<xs:element name="misfire-instruction" type="cron-trigger-misfire-instructionType" minOccurs="0" />
<xs:element name="cron-expression" type="cron-expressionType" />
<xs:element name="time-zone" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="calendarIntervalTriggerType">
<xs:annotation>
<xs:documentation>Define a DateIntervalTrigger</xs:documentation>
</xs:annotation>
<xs:complexContent>
<xs:extension base="abstractTriggerType">
<xs:sequence>
<xs:element name="misfire-instruction" type="date-interval-trigger-misfire-instructionType" minOccurs="0" />
<xs:element name="repeat-interval" type="xs:nonNegativeInteger" />
<xs:element name="repeat-interval-unit" type="interval-unitType" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:simpleType name="cron-expressionType">
<xs:annotation>
<xs:documentation>
Cron expression (see JavaDoc for examples)
Special thanks to Chris Thatcher (thatcher@butterfly.net) for the regular expression!
Regular expressions are not my strong point but I believe this is complete,
with the caveat that order for expressions like 3-0 is not legal but will pass,
and month and day names must be capitalized.
If you want to examine the correctness look for the [\s] to denote the
seperation of individual regular expressions. This is how I break them up visually
to examine them:
SECONDS:
(
((([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?,)*([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?)
| (([\*]|[0-9]|[0-5][0-9])/([0-9]|[0-5][0-9]))
| ([\?])
| ([\*])
) [\s]
MINUTES:
(
((([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?,)*([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?)
| (([\*]|[0-9]|[0-5][0-9])/([0-9]|[0-5][0-9]))
| ([\?])
| ([\*])
) [\s]
HOURS:
(
((([0-9]|[0-1][0-9]|[2][0-3])(-([0-9]|[0-1][0-9]|[2][0-3]))?,)*([0-9]|[0-1][0-9]|[2][0-3])(-([0-9]|[0-1][0-9]|[2][0-3]))?)
| (([\*]|[0-9]|[0-1][0-9]|[2][0-3])/([0-9]|[0-1][0-9]|[2][0-3]))
| ([\?])
| ([\*])
) [\s]
DAY OF MONTH:
(
((([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(-([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1]))?,)*([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(-([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1]))?(C)?)
| (([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])/([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(C)?)
| (L(-[0-9])?)
| (L(-[1-2][0-9])?)
| (L(-[3][0-1])?)
| (LW)
| ([1-9]W)
| ([1-3][0-9]W)
| ([\?])
| ([\*])
)[\s]
MONTH:
(
((([1-9]|0[1-9]|1[0-2])(-([1-9]|0[1-9]|1[0-2]))?,)*([1-9]|0[1-9]|1[0-2])(-([1-9]|0[1-9]|1[0-2]))?)
| (([1-9]|0[1-9]|1[0-2])/([1-9]|0[1-9]|1[0-2]))
| (((JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?,)*(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?)
| ((JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)/(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))
| ([\?])
| ([\*])
)[\s]
DAY OF WEEK:
(
(([1-7](-([1-7]))?,)*([1-7])(-([1-7]))?)
| ([1-7]/([1-7]))
| (((MON|TUE|WED|THU|FRI|SAT|SUN)(-(MON|TUE|WED|THU|FRI|SAT|SUN))?,)*(MON|TUE|WED|THU|FRI|SAT|SUN)(-(MON|TUE|WED|THU|FRI|SAT|SUN))?(C)?)
| ((MON|TUE|WED|THU|FRI|SAT|SUN)/(MON|TUE|WED|THU|FRI|SAT|SUN)(C)?)
| (([1-7]|(MON|TUE|WED|THU|FRI|SAT|SUN))(L|LW)?)
| (([1-7]|MON|TUE|WED|THU|FRI|SAT|SUN)#([1-7])?)
| ([\?])
| ([\*])
)
YEAR (OPTIONAL):
(
[\s]?
([\*])?
| ((19[7-9][0-9])|(20[0-9][0-9]))?
| (((19[7-9][0-9])|(20[0-9][0-9]))/((19[7-9][0-9])|(20[0-9][0-9])))?
| ((((19[7-9][0-9])|(20[0-9][0-9]))(-((19[7-9][0-9])|(20[0-9][0-9])))?,)*((19[7-9][0-9])|(20[0-9][0-9]))(-((19[7-9][0-9])|(20[0-9][0-9])))?)?
)
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:pattern
value="(((([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?,)*([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?)|(([\*]|[0-9]|[0-5][0-9])/([0-9]|[0-5][0-9]))|([\?])|([\*]))[\s](((([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?,)*([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?)|(([\*]|[0-9]|[0-5][0-9])/([0-9]|[0-5][0-9]))|([\?])|([\*]))[\s](((([0-9]|[0-1][0-9]|[2][0-3])(-([0-9]|[0-1][0-9]|[2][0-3]))?,)*([0-9]|[0-1][0-9]|[2][0-3])(-([0-9]|[0-1][0-9]|[2][0-3]))?)|(([\*]|[0-9]|[0-1][0-9]|[2][0-3])/([0-9]|[0-1][0-9]|[2][0-3]))|([\?])|([\*]))[\s](((([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(-([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1]))?,)*([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(-([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1]))?(C)?)|(([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])/([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(C)?)|(L(-[0-9])?)|(L(-[1-2][0-9])?)|(L(-[3][0-1])?)|(LW)|([1-9]W)|([1-3][0-9]W)|([\?])|([\*]))[\s](((([1-9]|0[1-9]|1[0-2])(-([1-9]|0[1-9]|1[0-2]))?,)*([1-9]|0[1-9]|1[0-2])(-([1-9]|0[1-9]|1[0-2]))?)|(([1-9]|0[1-9]|1[0-2])/([1-9]|0[1-9]|1[0-2]))|(((JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?,)*(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?)|((JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)/(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))|([\?])|([\*]))[\s]((([1-7](-([1-7]))?,)*([1-7])(-([1-7]))?)|([1-7]/([1-7]))|(((MON|TUE|WED|THU|FRI|SAT|SUN)(-(MON|TUE|WED|THU|FRI|SAT|SUN))?,)*(MON|TUE|WED|THU|FRI|SAT|SUN)(-(MON|TUE|WED|THU|FRI|SAT|SUN))?(C)?)|((MON|TUE|WED|THU|FRI|SAT|SUN)/(MON|TUE|WED|THU|FRI|SAT|SUN)(C)?)|(([1-7]|(MON|TUE|WED|THU|FRI|SAT|SUN))?(L|LW)?)|(([1-7]|MON|TUE|WED|THU|FRI|SAT|SUN)#([1-7])?)|([\?])|([\*]))([\s]?(([\*])?|(19[7-9][0-9])|(20[0-9][0-9]))?| (((19[7-9][0-9])|(20[0-9][0-9]))/((19[7-9][0-9])|(20[0-9][0-9])))?| ((((19[7-9][0-9])|(20[0-9][0-9]))(-((19[7-9][0-9])|(20[0-9][0-9])))?,)*((19[7-9][0-9])|(20[0-9][0-9]))(-((19[7-9][0-9])|(20[0-9][0-9])))?)?)" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="repeat-countType">
<xs:annotation>
<xs:documentation>Number of times to repeat the Trigger (-1 for indefinite)</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:integer">
<xs:minInclusive value="-1" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="simple-trigger-misfire-instructionType">
<xs:annotation>
<xs:documentation>Simple Trigger Misfire Instructions</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:pattern value="SmartPolicy" />
<xs:pattern value="RescheduleNextWithExistingCount" />
<xs:pattern value="RescheduleNextWithRemainingCount" />
<xs:pattern value="RescheduleNowWithExistingRepeatCount" />
<xs:pattern value="RescheduleNowWithRemainingRepeatCount" />
<xs:pattern value="FireNow" />
<xs:pattern value="IgnoreMisfirePolicy" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="cron-trigger-misfire-instructionType">
<xs:annotation>
<xs:documentation>Cron Trigger Misfire Instructions</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:pattern value="SmartPolicy" />
<xs:pattern value="DoNothing" />
<xs:pattern value="FireOnceNow" />
<xs:pattern value="IgnoreMisfirePolicy" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="date-interval-trigger-misfire-instructionType">
<xs:annotation>
<xs:documentation>Date Interval Trigger Misfire Instructions</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:pattern value="SmartPolicy" />
<xs:pattern value="DoNothing" />
<xs:pattern value="FireOnceNow" />
<xs:pattern value="IgnoreMisfirePolicy" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="interval-unitType">
<xs:annotation>
<xs:documentation>Interval Units</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:pattern value="Day" />
<xs:pattern value="Hour" />
<xs:pattern value="Minute" />
<xs:pattern value="Month" />
<xs:pattern value="Second" />
<xs:pattern value="Week" />
<xs:pattern value="Year" />
</xs:restriction>
</xs:simpleType>
</xs:schema>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Common.Logging" version="3.3.1" targetFramework="net40" />
<package id="Common.Logging.Core" version="3.3.1" targetFramework="net40" />
<package id="log4net" version="2.0.8" targetFramework="net40" requireReinstallation="true" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net451" />
<package id="Quartz" version="2.6.2" targetFramework="net40" />
</packages>

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8" ?>
<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData">
<processing-directives>
<overwrite-existing-data>true</overwrite-existing-data>
</processing-directives>
<schedule>
<!--订阅数据任务-->
<job>
<name>JobSendBooking</name>
<group>Job</group>
<description>订阅数据</description>
<job-type>JobSendAgentMail.JobSendCtn,JobSendAgentMail</job-type>
<durable>true</durable>
<recover>false</recover>
<job-data-map>
<!--连接字符串-->
<entry>
<key>ConnectString</key>
<value>Data Source=119.167.78.10,1433;Initial Catalog=DATA;Persist Security Info=True;User ID=sa;Password=yongfa_123</value>
</entry>
<!--查询SQL-->
<entry>
<key>QuerySql</key>
<value>
SELECT 箱号 FROM [dbo].[t_op_ctn_detail] where isnull(是否还箱,0)=0 and (GETDATE()-动态时间)>180
</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILSENDACCOUNT</key>
<value>han_xuntao@163.com</value>
</entry>
<!--DS7邮箱发送密码-->
<entry>
<key>MAILSENDPASSWORD</key>
<value>ds20040201</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILSENDSERVICE</key>
<value>smtp.163.com</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILSENDPORT</key>
<value>25</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILISSSL</key>
<value>false</value>
</entry>
<entry>
<key>MAILRECEIVER</key>
<value>e.control@win-fast.com.cn,e.control2@win-fast.com.cn</value>
</entry>
<entry>
<key>MAILTITLE</key>
<value>集装箱超期提醒</value>
</entry>
</job-data-map>
</job>
<!-- 发送请求数据任务触发器-->
<trigger>
<cron>
<name>TriggerBooking</name>
<group>Job</group>
<description>订阅数据触发器</description>
<job-name>JobSendBooking</job-name>
<job-group>Job</job-group>
<cron-expression>0 55 14 * * ?</cron-expression>
</cron>
</trigger>
</schedule>
</job-scheduling-data>

@ -0,0 +1,103 @@
<?xml version="1.0" encoding="utf-8" ?>
<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData">
<processing-directives>
<overwrite-existing-data>true</overwrite-existing-data>
</processing-directives>
<schedule>
<!--订阅数据任务-->
<job>
<name>JobSendBooking</name>
<group>Job</group>
<description>订阅数据</description>
<job-type>JobSendAgentMail.JobSendBooking,JobSendAgentMail</job-type>
<durable>true</durable>
<recover>false</recover>
<job-data-map>
<!--连接字符串-->
<entry>
<key>ConnectString</key>
<value>Data Source=www.perways.net,18866;Initial Catalog=ShippingWeb_SZYT;Persist Security Info=True;User ID=sa;Password=Ds20040201</value>
</entry>
<!--查询SQL-->
<entry>
<key>QuerySql</key>
<value>
select BSNO,MBLNO,ORDERNO,OPERATORFAX AS BLREMARK,AGENTID,BLFRT,PORTLOAD,PORTDISCHARGE,DESTINATION,CONVERT(varchar(100), ETD, 23) AS ETD,ATD,HBLNO,CONVERT(varchar(100), ETA, 23) ETA,CNTRTOTAL,(
SELECT CODENAME FROM info_client WHERE SHORTNAME=OP_SEAE.CARRIER) CARRIERID,(CASE WHEN ISSUETYPE='电放' then 'Telex release'else case when ISSUETYPE='正本' then 'Original Bill' else case when ISSUETYPE='SWB' then 'Seaway Bill' else case when issuetype='云提单'then'INTELLIGENT BL'else '' end end end end) ISSUETYPE,(SELECT TOP 1 USERNAME FROM [user] where SHOWNAME=op_seae.OP) OPNAME,(SELECT TOP 1 email1 FROM [VW_user] where SHOWNAME=op_seae.OP) OPEMAIL, (((SELECT TOP 1 EMAIL FROM info_client where SHORTNAME=op_seae.AGENTID ))+';'+( SELECT TOP 1 email1 FROM [VW_userquan] where SHOWNAME=op_seae.SALE )) AGENTEMAIL from op_seae WHERE custno like 'CXE22050397'
</value>
</entry>
<entry>
<key>HblQuerySql</key>
<value>
select HBLNO,(CASE WHEN ISSUETYPE='电放' then 'Telex release'else
case when ISSUETYPE='正本' then 'Original Bill' else case when ISSUETYPE='SWB' then 'Seaway Bill' else case when issuetype='云提单'then'INTELLIGENT BL'else '' end end end end ) ISSUETYPE
from op_seae_billmanage
</value>
</entry>
<!--单据类型-->
<entry>
<key>DocType</key>
<value>PA</value>
</entry>
<!--DS7绝对路径-->
<entry>
<key>D7FilePath</key>
<value>D:\东胜\DONGSHENGWEB\</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILSENDACCOUNT</key>
<value>szytcus@perways.com</value>
</entry>
<!--DS7邮箱发送密码-->
<entry>
<key>MAILSENDPASSWORD</key>
<value>PER202100558YT12</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILSENDSERVICE</key>
<value>smtp.263.net</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILSENDPORT</key>
<value>25</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILISSSL</key>
<value>false</value>
</entry>
<entry>
<key>MAILTEMPLATE</key>
<value>MailTemplate.html</value>
</entry>
</job-data-map>
</job>
<!-- 发送请求数据任务触发器-->
<trigger>
<cron>
<name>TriggerBooking</name>
<group>Job</group>
<description>订阅数据触发器</description>
<job-name>JobSendBooking</job-name>
<job-group>Job</job-group>
<cron-expression>0 34 14 * * ?</cron-expression>
</cron>
</trigger>
<!--<trigger>
<simple>
<name>TriggerBooking</name>
<group>Job</group>
<description>订阅数据触发器</description>
<job-name>JobSendBooking</job-name>
<job-group>Job</job-group>
<cron-expression>0 5,10 9 * * ?</cron-expression>
</simple>
</trigger>-->
</schedule>
</job-scheduling-data>

Binary file not shown.

Binary file not shown.

@ -0,0 +1,210 @@
using log4net;
using Quartz;
using System;
using System.Data;
using System.Data.SqlClient;
using RabbitMQ.Client;
using System.IO;
using System.Linq;
using System.Text;
using MailKit.Net.Smtp;
using MimeKit;
using HtmlAgilityPack;
using System.Collections.Generic;
using System.Configuration;
using System.Threading.Tasks;
using System.Threading;
using Newtonsoft.Json;
namespace JobSendAgentMail
{
public class MsOpSeae
{
public string BSNO { get; set; }
public string MBLNO { get; set; }
public string OP { get; set; }
public string MAIL { get; set; }
}
public class SendMail
{
public string OP { get; set; }
public string MAIL { get; set; }
public string MAILDESCRIPTION { get; set; }
}
public class JobDjy2D7Date : IJob
{
private ILog log = LogManager.GetLogger(typeof(JobDjy2D7Date));
private static IConnection mqConn;
public void Execute(IJobExecutionContext context)
{
string connStr = context.JobDetail.JobDataMap.GetString("ConnectString");
string MQURL = context.JobDetail.JobDataMap.GetString("DJYMQURL");
string virtualhost = context.JobDetail.JobDataMap.GetString("virtualhost");
string ExchangeName = context.JobDetail.JobDataMap.GetString("MQExchangeName");
string QueueName = context.JobDetail.JobDataMap.GetString("MQQueueName");
string BSSQL = context.JobDetail.JobDataMap.GetString("BSSQL");
string MAILSENDACCOUNT = context.JobDetail.JobDataMap.GetString("MAILSENDACCOUNT");
string MAILSENDPASSWORD = context.JobDetail.JobDataMap.GetString("MAILSENDPASSWORD");
string MAILSENDSERVICE = context.JobDetail.JobDataMap.GetString("MAILSENDSERVICE");
string MAILSENDPORT = context.JobDetail.JobDataMap.GetString("MAILSENDPORT");
string MAILISSSL = context.JobDetail.JobDataMap.GetString("MAILISSSL");
log.Debug($"启动接收大简云数据回推");
var CompanyQueueName = QueueName;
ConnectionFactory factory = new ConnectionFactory();
factory.Uri = new Uri(MQURL);
//factory.UserName = "xgs_test";
//factory.Password = "xgs_test123";
factory.VirtualHost = virtualhost;
mqConn = factory.CreateConnection();
IModel model = mqConn.CreateModel();
var task = Task.Run(() =>
{
while (true)
{
var result = model.BasicGet(queue: CompanyQueueName, autoAck: true);
if (result == null) { Thread.Sleep(10); continue; };
var strBody = Encoding.UTF8.GetString(result.Body.ToArray());
log.Debug($"收到简云截单日期数据回推消息:{strBody}");
try
{
//回写数据
var dateback = JsonConvert.DeserializeAnonymousType(strBody, new { vessel = string.Empty, voyage = string.Empty, ship_agency = string.Empty, cut_off_time = string.Empty, etd = string.Empty });
if (!string.IsNullOrEmpty(dateback.vessel) && !string.IsNullOrEmpty(dateback.voyage) && !string.IsNullOrEmpty(dateback.ship_agency) && !string.IsNullOrEmpty(dateback.cut_off_time))
{
using (SqlConnection dbcon = new SqlConnection(connStr))
{
dbcon.Open();
string maildescrption = "";
var FORWARDER = GetCustEdi(dbcon, dateback.ship_agency);
var SendMailList = new List<SendMail>();
if (!string.IsNullOrEmpty(FORWARDER))
{
var opseaelist = GetBs(dbcon, "VESSEL='" + dateback.vessel + "' AND VOYNO='" + dateback.voyage + "' and FORWARDER='" + FORWARDER + "'" + BSSQL);
if (opseaelist != null && opseaelist.Count != 0)
{
var opemail = "";
foreach (var opseae in opseaelist)
{
var tastStr = $" update op_seae set CLOSEDOCDATE='{dateback.cut_off_time}' where BSNO='{opseae.BSNO}' ";
SqlCommand cmdtast = new SqlCommand(tastStr, dbcon);
cmdtast.ExecuteNonQuery();
log.Debug($"已更新截单日期{dateback.cut_off_time},{opseae.MBLNO},{opseae.BSNO}");
var sendmail = SendMailList.Find(x => x.OP == opseae.OP);
if (sendmail != null)
{
sendmail.MAILDESCRIPTION = sendmail.MAILDESCRIPTION + Environment.NewLine + opseae.MBLNO;
}
else
{
var newsendmail = new SendMail();
newsendmail.OP = opseae.OP;
newsendmail.MAIL = opseae.MAIL;
newsendmail.MAILDESCRIPTION = opseae.MBLNO;
SendMailList.Add(newsendmail);
}
}
}
}
else
{
log.Debug($"{dateback.ship_agency}没有找到对应的订舱代理");
}
if (SendMailList != null && SendMailList.Count != 0)
{
foreach (var SendMail in SendMailList)
{
SendEmail se = new SendEmail(SendMail.MAIL, MAILSENDACCOUNT, "", "", "截港日期自动更新", SendMail.MAILDESCRIPTION, false);
se.SetSmtp(MAILSENDACCOUNT, MAILSENDPASSWORD, MAILSENDSERVICE, Convert.ToInt16(MAILSENDPORT), false, System.Net.Mail.MailPriority.Normal); //必须在所有参数设置完后调用此方法
log.Debug($"已给操作{SendMail.OP}发送邮件{SendMail.MAIL}{SendMail.MAILDESCRIPTION}");
}
}
}
}
}
catch (Exception ex)
{
log.Error($"处理大简云数据回推时出错:" + ex.Message);
log.Error(ex.Message);
log.Error(ex.StackTrace);
}
//model.BasicConsume(CompanyQueueName, true, consumer);
//Console.WriteLine(msg);
}
});
task.Wait();
model.Close();
mqConn.Close();
}
static public List<MsOpSeae> GetBs(SqlConnection dbcon, string constr)
{
var opseaeList = new List<MsOpSeae>();
var strSql = new StringBuilder();
strSql.Append("select BSNO,MBLNO,OP,FORWARDER,(SELECT TOP 1 EMAIL1 FROM VW_user WHERE SHOWNAME=op_seae.OP) EMAIL from op_seae where " + constr);
strSql.Append(" ORDER BY OP ");
SqlDataAdapter adapter = new SqlDataAdapter(strSql.ToString(), dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
var opseae = new MsOpSeae();
opseae.BSNO = Convert.ToString(row["BSNO"].ToString());
opseae.MBLNO = Convert.ToString(row["MBLNO"].ToString());
opseae.OP = Convert.ToString(row["OP"].ToString());
opseae.MAIL = Convert.ToString(row["EMAIL"].ToString());
opseaeList.Add(opseae);
}
}
return opseaeList;
}
static public string GetCustEdi(SqlConnection dbcon, string constr)
{
string result = "";
var strSql = new StringBuilder();
strSql.Append("select CUST from code_cust_edi where EDINAME='DJY' AND EDICODE='" + constr + "'");
SqlDataAdapter adapter = new SqlDataAdapter(strSql.ToString(), dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
result = Convert.ToString(row["CUST"].ToString());
}
}
return result;
}
}
}

@ -0,0 +1,103 @@
<?xml version="1.0" encoding="utf-8" ?>
<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData">
<processing-directives>
<overwrite-existing-data>true</overwrite-existing-data>
</processing-directives>
<schedule>
<!--订阅数据任务-->
<job>
<name>JobSendBooking</name>
<group>Job</group>
<description>订阅数据</description>
<job-type>JobSendAgentMail.JobSendBooking,JobSendAgentMail</job-type>
<durable>true</durable>
<recover>false</recover>
<job-data-map>
<!--连接字符串-->
<entry>
<key>ConnectString</key>
<value>Data Source=www.perways.net,18866;Initial Catalog=ShippingWeb_SZYT;Persist Security Info=True;User ID=sa;Password=Ds20040201</value>
</entry>
<!--查询SQL-->
<entry>
<key>QuerySql</key>
<value>
select BSNO,MBLNO,ORDERNO,OPERATORFAX AS BLREMARK,AGENTID,BLFRT,PORTLOAD,PORTDISCHARGE,DESTINATION,CONVERT(varchar(100), ETD, 23) AS ETD,ATD,HBLNO,CONVERT(varchar(100), ETA, 23) ETA,CNTRTOTAL,(
SELECT CODENAME FROM info_client WHERE SHORTNAME=OP_SEAE.CARRIER) CARRIERID,(CASE WHEN ISSUETYPE='电放' then 'Telex release'else case when ISSUETYPE='正本' then 'Original Bill' else case when ISSUETYPE='SWB' then 'Seaway Bill' else case when issuetype='云提单'then'INTELLIGENT BL'else '' end end end end) ISSUETYPE,(SELECT TOP 1 USERNAME FROM [user] where SHOWNAME=op_seae.OP) OPNAME,(SELECT TOP 1 email1 FROM [VW_user] where SHOWNAME=op_seae.OP) OPEMAIL, (((SELECT TOP 1 EMAIL FROM info_client where SHORTNAME=op_seae.AGENTID ))+';'+( SELECT TOP 1 email1 FROM [VW_userquan] where SHOWNAME=op_seae.SALE )) AGENTEMAIL from op_seae WHERE custno like 'CXE22050397'
</value>
</entry>
<entry>
<key>HblQuerySql</key>
<value>
select HBLNO,(CASE WHEN ISSUETYPE='电放' then 'Telex release'else
case when ISSUETYPE='正本' then 'Original Bill' else case when ISSUETYPE='SWB' then 'Seaway Bill' else case when issuetype='云提单'then'INTELLIGENT BL'else '' end end end end ) ISSUETYPE
from op_seae_billmanage
</value>
</entry>
<!--单据类型-->
<entry>
<key>DocType</key>
<value>PA</value>
</entry>
<!--DS7绝对路径-->
<entry>
<key>D7FilePath</key>
<value>D:\东胜\DONGSHENGWEB\</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILSENDACCOUNT</key>
<value>szytcus@perways.com</value>
</entry>
<!--DS7邮箱发送密码-->
<entry>
<key>MAILSENDPASSWORD</key>
<value>PER202100558YT12</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILSENDSERVICE</key>
<value>smtp.263.net</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILSENDPORT</key>
<value>25</value>
</entry>
<!--DS7邮箱发送账号-->
<entry>
<key>MAILISSSL</key>
<value>false</value>
</entry>
<entry>
<key>MAILTEMPLATE</key>
<value>MailTemplate.html</value>
</entry>
</job-data-map>
</job>
<!-- 发送请求数据任务触发器-->
<trigger>
<cron>
<name>TriggerBooking</name>
<group>Job</group>
<description>订阅数据触发器</description>
<job-name>JobSendBooking</job-name>
<job-group>Job</job-group>
<cron-expression>0 34 14 * * ?</cron-expression>
</cron>
</trigger>
<!--<trigger>
<simple>
<name>TriggerBooking</name>
<group>Job</group>
<description>订阅数据触发器</description>
<job-name>JobSendBooking</job-name>
<job-group>Job</job-group>
<cron-expression>0 5,10 9 * * ?</cron-expression>
</simple>
</trigger>-->
</schedule>
</job-scheduling-data>
Loading…
Cancel
Save