Use C # and Java to send emails

Source: Internet
Author: User

 

When registering a user, you must activate the account by email. In this case, you must use the program email technology. The following is a common method for sending mails in projects:

[C #]

1 usingSystem. Net. Mail;
2 usingSystem. Net;
3
4 publicclassEmailEntity
5 {
6 privateMailMessage mm;
7
8 /// <summary>
9 // send an email
10 /// </summary>
11 publicvoidsendMessage ()
12 {
13
14 // specify the sender's email address
15 MailAddress fromAddress = newMailAddress ("abc@163.com ");
16 // specify the recipient's email address
17 MailAddress toAddress = newMailAddress ("efg@qq.com ");
18 // create an email object
19mm = newMailMessage (fromAddress, toAddress );
20 // Add a BCC email address
21mm. Bcc. Add (newMailAddress ("xiuxiu@qq.com "));
22 // Add a CC email address
23mm. CC. Add (newMailAddress ("me@qq.com "));
24 // specify the encoding format of the mail title
25mm. SubjectEncoding = Encoding. UTF8;
26 // set the mail title
27mm. Subject = "I am the title ";
28 // specify the email body code

29mm. BodyEncoding = Encoding. UTF8;
30 // specify whether the email body is of the text or html type
31mm. IsBodyHtml = true;
32 // set the body of the email
33mm. Body = "<span style = 'color: # ff0000; font-weight: bold; '> I love xiuxiu! </Span> ";
34 // create an attachment
35 Attachment file = newAttachment (AppDomain. CurrentDomain. BaseDirectory + "xiuxiu.jpg ");
36 // set the attachment creation date
37 file. ContentDisposition. CreationDate = DateTime. Now;
38 // set the attachment type
39 file. ContentType = newSystem. Net. Mime. ContentType ("image/jpeg ");
40 // Add the attachment to the email
41mm. Attachments. Add (file );
42
43 // specify the address and port number of the email sending server
44 SmtpClient SC = newSmtpClient ("smtp.163.com", 25 );
45 // specify the sender's authentication information
46 SC. Credentials = newNetworkCredential ("abc", "123456 ");
47 // SC. Send (mm );
48 // register an asynchronous sending event
49 SC. SendCompleted + = newSendCompletedEventHandler (SC _SendCompleted );
50 // start executing asynchronous mail sending
51 SC. SendAsync (mm, null );
52}
53 // process the event upon completion of asynchronous mail sending
54 voidsc_SendCompleted (objectsender, System. ComponentModel. AsyncCompletedEventArgs e)
55 {
56 if (mm! = Null)

57 {
58mm. Dispose (); // release resources
59}
60 if (e. Cancelled)
61 {
62 Console. WriteLine ("User canceled! ");
63}
64 elseif (e. Error! = Null)
65 {
66 Console. WriteLine ("failed to send because:" + e. Error. Message );
67}
68 else
69 {
70 Console. WriteLine ("sent successfully! ");
71}
72}
73}

[Java]

1importjava. util. Date;
2importjava. util. Properties;
3importjavax. mail. Authenticator;
4importjavax. mail. PasswordAuthentication;
5importjavax. mail. Message. RecipientType;
6importjavax. mail. MessagingException;
7importjavax. mail. Session;
8importjavax. mail. Transport;
9importjavax. mail. internet. AddressException;
10importjavax. mail. internet. InternetAddress;
11importjavax. mail. internet. MimeMessage;
12importjavax. mail. internet. MimeMultipart;

13
14 /**
15 * Email entity class, which encapsulates the methods for sending emails.
16 * @ authorxxxxxx
17 *
18 */
19 publicclassEmailEntity {
20
21 privateMimeMessage msg;
22
23 /**
24 * initialize the email entity
25 *
26 * @ paramfromDomin
27 * the sender's email server domain name, such as 163.comand qq.com.
28 * @ paramuserName
29 * sender username, such as qmail and 20082345
30 * @ parampassword
31 * sender Password
32 * @ paramtoAddress
33 * recipient email address, e.g.: 200712345@qq.com
34 */
35 publicEmailEntity (String fromDomin, String userName, String password ){
36 Properties p = newProperties ();
37 // set the email sending server address
38 p. setProperty ("mail. host", "smtp." + fromDomin );
39 // set permission Verification
40 p. setProperty ("mail. smtp. auth", "true ");
41 // Set User Authentication creden
42 Session ses = Session. getDefaultInstance (p, newMyAuthentic

Ator (userName, password ));
43 // ses. setDebug (true); // you can specify whether the ECHO is displayed.
44 // create email entity
45 msg = newMimeMessage (ses );
46 try {
47 // set the sender's email address
48 msg. setFrom (newInternetAddress (userName + "@" + fromDomin ));
49} catch (AddressException e ){
50 e. printStackTrace ();
51} catch (MessagingException e ){
52 e. printStackTrace ();
53}
54}
55
56 /**
57 * send messages
58 *
59 * @ paramtitle
60 * mail title
61 * @ paramcontent
62 * body of email
63 * @ paramtype
64 * body type, such as text/html and text/plain
65 * @ return
66 */
67 publicbooleansendMessage (String toAddress, String title, String content, String type ){
68
69 try {
70 // set the sender's email address
71 msg. setRecipient (RecipientType. TO, newInternetAddress

(ToAddress ));
72 // set the mail sending date
73 msg. setSentDate (newDate ());
74 // set the mail title
75 msg. setSubject (title );
76 // set the mail body
77 msg. setContent (content, type );
78 // start sending emails
79 Transport. send (msg );
80 returntrue;
81} catch (MessagingException ex ){
82 ex. printStackTrace ();
83 returnfalse;
84}
85}
86
87 /**
88 * send emails with attachments
89 * @ paramtoAddress the recipient's email address, such as the suxibo@126.com
90 * @ paramtitle: email title
91 * @ paramcontent body of the email, including attachments
92 * @ paramtype the mail body type
93 * @ return
94 */
95 publicbooleansendEmailWithAttachment (String toAddress, String title, MimeMultipart content, String type ){
96 try {
97 msg. setRecipient (RecipientType. TO, newInternetAddress (toAddress ));
98 msg. setSentDate (newDate ());
99 msg. setSubject (title );
100 msg. setContent (content );
101 Transport. send (msg );

102 returntrue;
103} catch (MessagingException ex ){
104 ex. printStackTrace ();
105 returnfalse;
106}
107}
108}
109
110 // user authentication credential class
111 classMyAuthenticator extendsAuthenticator {
112
113 privateString _ userName;
114 privateString _ password;
115
116 publicMyAuthenticator (String userName, String password ){
117 this. _ userName = userName;
118 this. _ password = password;
119}
120
121 @ Override
122 publicPasswordAuthentication getPasswordAuthentication (){
123 // return the authentication creden with the user name and password
124 returnnewPasswordAuthentication (_ userName, _ password );
125}
126}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.