For the first time, I used this method to send an email. For example, I used my live mailbox to send an email to my QQ mailbox.
The steps for sending an email using smtpclient will not be discussed. You can find too many information on the Internet. Here are some notes:
If the email content is HTML, set mailmessage. isbodyhtml to true so that the email can be correctly read in HTML format.
The reference resource in HTML uses CID: XXX. XXX is the contentid attribute of the attachment. You can also add alternateview to alternateviews in mailmessage to specify different formats of email content. You can add the referenced files through the temporary resources of alternativeview. The reference is also set through the contentid of volume resource. In fact, the contentid attribute comes from the attachmentbase type, while the attachment, alternateview, and resourcetypes both inherit from this class:
In addition, if the email content, subject, and address name contain some non-ASCII characters, you should specify an encoding because the default encoding is ASCII.
Some SMTP servers may not support SSL transmission. Therefore, the enablessl of smtpclient can only be set to false (otherwise, an exception is thrown ).
Code:
Using system;
Using system. text;
Using system. net;
Using system. net. Mime;
Using system. net. mail;
Namespace mgen
{
Class Program
{
Static void main ()
{
// Some information in the Code (such as the email address and password) has been replaced by XXX. Therefore, if you compile the code, replace it with valid data first!
Using (var smtp = new smtpclient ())
Using (VAR mail = new mailmessage ("xxx@live.com", "xxx@qq.com "))
{
// Image Attachment
VaR attach = new attachment (@ "D: \ a.jpg", mediatypenames. image. JPEG );
// Set contentid
Attach. contentid = "pic ";
// Zip attachment
VaR attach2 = new attachment (@ "D: \ B .zip", "application/X-zip-compressed ");
Mail. attachments. Add (attach );
Mail. attachments. Add (attach2 );
// Set the title and content because the default encoding is ASCII.
Mail. Subject = "hello ";
Mail. subjectencoding = encoding. utf8;
// HTML content
Mail. Body = " <p> from mgen. </P> ";
Mail. bodyencoding = encoding. utf8;
// Instruct to change the email content to HTML Format
Mail. isbodyhtml = true;
// SMTP settings (this is the SMTP server address of Live Mail Based on the mailbox type)
SMTP. Host = "smtp.live.com ";
SMTP. usedefacrecredentials = false;
// Some SMTP servers may not support SSL and will throw an exception
SMTP. enablessl = true;
SMTP. Credentials = new networkcredential ("xxx@live.com", "XXX ");
SMTP. deliverymethod = smtpdeliverymethod. Network;
// Send
SMTP. Send (Mail );
}
}
}
}
Finally, browse the received emails in the QQ mailbox: