如何为此代码添加附件 [英] How do I add an attachment to this code

查看:93
本文介绍了如何为此代码添加附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将C:\ path\Word.docx中的附件添加到此代码中:



How do I add an attachment from "C:\path\Word.docx" to this code:

MailMessage msg = New MailMessage ();
MailAddress fromAdd = New MailAddress("fromemail@email.com");
msg.[To].Add("toemail@email.com");
msg.Subject = "Choose Session Members";
msg.From = fromAdd;
msg .IsBodyHtml = True;
msg.Priority = MailPriority.Normal;
msg .BodyEncoding = Encoding.Default;
msg.Body = "<center><table><tr><td><h1>Your Message</h1><br/><br/></td></tr>";
msg.Body = msg.Body + "</table></center>";
SmtpClient smtpClient = New SmtpClient ("smtp.yourserver.com", "25");
smtpClient.EnableSsl = True;
smtpClient.UseDefaultCredentials = False;
smtpClient.Credentials = New System.Net.NetworkCredential("smtpserver@yourserver.com", "password");
smtpClient .DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(msg);
smtpClient.Dispose();

推荐答案

使用以下代码使用附件发送邮件:



Use the Following Code to Send mail Using Attachment:

using System;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
	protected void Button1_Click(object sender, EventArgs e)
	{
		string attachmentFile = null ;
		if (FileUpload1.HasFile)
		{
			try
			{
				FileUpload1.SaveAs("C:\\files\\" + FileUpload1.FileName);
				attachmentFile = FileUpload1.PostedFile.FileName;
			}
			catch (Exception ex)
			{
				Label1.Text = "File Upload Failed !! " + ex.Message.ToString();
			}

			try
			{
				MailMessage mail = new MailMessage();
				SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

				mail.From = new MailAddress("your-gamila-ddress@gmail.com"); //you have to provide your gmail address as from address
				mail.To.Add(to_txt.Text);
				mail.Subject = subject_txt.Text;
				mail.Body = message_txt.Text;

				System.Net.Mail.Attachment attachment;
				attachment = new System.Net.Mail.Attachment(attachmentFile);
				mail.Attachments.Add(attachment);

				SmtpServer.Port = 587;
				SmtpServer.Credentials = new System.Net.NetworkCredential("gamil-username", "gmail-passowrd"); //you have to provide you gamil username and password
				SmtpServer.EnableSsl = true;

				SmtpServer.Send(mail);
				Label1.Text = "Email successfully sent.";
			}
			catch (Exception ex)
			{
				Label1.Text = "Mail Send Failed !! " + ex.Message.ToString();
			}
		}
		else
		{
			Label1.Text = "Please select a file for uploading";
		}
	}
}


这篇关于如何为此代码添加附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆