如何每60分钟用c#发送一个文件到Email或ftp

时间:2014-12-07 14:19:00

标签: c# email ftp smtp

我想知道如何将带有C#的log.txt文件发送到我的电子邮件或FTP服务器。

我搜索谷歌,我什么也没找到,好吧,其实我发现了一些东西,但他们没有工作。

我在微软网站上找到了这段代码,但我真的不明白它是如何知道smtp服务器地址或我的用户名和密码的。我也不知道如何让它每60分钟(1小时)发送一次文件。

public static void CreateMessageWithAttachment(string server)
{
    // Specify the file to be attached and sent. 
    // This example assumes that a file named Data.xls exists in the 
    // current working directory. 
    string file = "log.txt";
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
           "shaked6540@hotmail.com",
           "shaked6540@hotmail.com",
           "Quarterly data report.",
           "See the attached spreadsheet.");

    // Create  the file attachment for this e-mail message.
    Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
    // Add time stamp information for the file.
    ContentDisposition disposition = data.ContentDisposition;
    disposition.CreationDate = System.IO.File.GetCreationTime(file);
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
    disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
    // Add the file attachment to this e-mail message.
    message.Attachments.Add(data);

    //Send the message.
    SmtpClient client = new SmtpClient(server);
    // Add credentials if the SMTP server requires them.
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
              ex.ToString());
    }
    // Display the values in the ContentDisposition for the attachment.
    ContentDisposition cd = data.ContentDisposition;
    Console.WriteLine("Content disposition");
    Console.WriteLine(cd.ToString());
    Console.WriteLine("File {0}", cd.FileName);
    Console.WriteLine("Size {0}", cd.Size);
    Console.WriteLine("Creation {0}", cd.CreationDate);
    Console.WriteLine("Modification {0}", cd.ModificationDate);
    Console.WriteLine("Read {0}", cd.ReadDate);
    Console.WriteLine("Inline {0}", cd.Inline);
    Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
    foreach (DictionaryEntry d in cd.Parameters)
    {
        Console.WriteLine("{0} = {1}", d.Key, d.Value);
    }
    data.Dispose();
}

1 个答案:

答案 0 :(得分:0)

  

但我真的不明白它是如何知道smtp服务器地址或我的用户名和密码的。

您需要提供smtp服务器地址和凭证(用户名/密码),

//Send the message.
SmtpClient client = new SmtpClient("smtp.live.com"); //the smtp server address
// Add credentials if the SMTP server requires them.
client.Credentials = new System.Net.NetworkCredential("shaked6540@hotmail.com", @yourpassword);

将程序编译成可执行文件。

  

我也不知道如何让它每60分钟(1小时)发送一次文件

作为Hans Passant的评论,创建一个期刊任务,每隔60分钟用Windows Task Scheduler运行exe。

或者您可以setup a timer定期发送电子邮件,但这种方法要求您的程序一直在运行。