这段代码有什么问题?此程序旨在复制文件并通过电子邮件发送到电子邮件地址,但事实并非如此。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
}
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail@gmail.com");
mail.To.Add("to_mail@gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail@gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
}
这显示以下编译器错误:
我该怎么办?
答案 0 :(得分:19)
email_send()
方法在类声明之外。它仍在命名空间内,但您还必须将其放在类中。此外,该方法从未被调用过。这是死代码。
在类定义中移动方法,然后从Form_Load()
中调用该方法答案 1 :(得分:5)
正是其他人的意思,但剪切/粘贴这个,你应该纠正错误:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.
using System.Net;
using System.Net.Mail;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail@gmail.com");
mail.To.Add("to_mail@gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail@gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
}
}
如您所见,您的email_send
方法现在位于类声明中。
答案 2 :(得分:2)
You Method在课堂之外是一件事。将其复制到表单1类中,它应该清除任何智能感知问题
答案 3 :(得分:1)
email_send方法未在类中定义。