Today I learned to write a simple email.ProgramIs sent using the SMTP server of IIS (the jmail component is used for the next step). After testing, an email is successfully sent to your mailbox. I feel very interesting. I hope I can write software similar to Foxmail in the future. Well, come on ~~~
1. Install the SMTP service
Install this component: 'Control panel '-> 'add or delete project'-> 'add or delete windows components'-> 'application Server'-> 'Internet Information Service (IIS)'->SMTP Service
2. Configure the SMTP Virtual Machine
On the 'Control panel '-> 'administrative tools'-> 'iis manager'-> 'default SMTP vserver'-> 'properties', enter the local IP address, select other items as needed.
3. Design the email sending Interface
Recipient: tbreceiver
Sender: tbsender
Sender email Username: tbsenderusername
Sender's email password: tbsenderpsw
Topic: tbsubject
Content: tbcontent
Attachment: fuattachment// Fileupload Control
Send: btnsend
4. Main ApplicationSystem. net. MailClass to write the mail sending program
MainCodeAs follows:
// Introduce three namespaces
Using system. IO;
Using system. net. mail;
Using system. net. Mime;
Protected void btnsend_click (Object sender, eventargs E)
{
Try
{
If (this. tbreceiver. Text! = String. Empty & this. tbsender. Text! = String. Empty)
{
// Create an email
Mailmessage mymail = new mailmessage (this. tbsender. text. trim (), this. tbreceiver. text. trim (), this. tbsubject. text. trim (), this. tbcontent. text. trim ());
Mymail. Priority = mailpriority. High;
// Create an attachment
If (this. fuattach. filename! = NULL)
{
String filepath = This. fuattachment. postedfile. filename;
Fileinfo Fi = new fileinfo (filepath );
If (Fi. exists)
{
Attachment myattachment = new attachment (filepath, mediatypenames. application. octet );
Contentdisposition disposition = myattachment. contentdisposition;
Disposition. creationdate = file. getcreationtime (filepath );
Disposition. modificationdate = file. getlastwritetime (filepath );
Disposition. readdate = file. getlastaccesstime (filepath );
Mymail. attachments. Add (myattachment );
}
}
// Send the attachment
Smtpclient client = new smtpclient ("smtp.163.com", 25 );
Client. Credentials = new system. net. networkcredential (this. tbuser. Text. Trim (), this. tbpsw. Text. Trim ());
Client. Send (mymail );
Response. Redirect ("mailinfo. aspx ");// Sending success prompt page
}
}
Catch
{
Response. Write ("<font color = Red> email sending failed! Possible cause: 1) Recipient address does not exist 2) sender address does not exist 3) User Name or Password error </font> ");// Error message prompt
}
Finally
{}
}