Reputation: 327
I added a page to my website that should send an email to my gmail account once a user submits a message with their email address. I want to set msg.from part of the code to be whatever the user puts in the txtEmail.text section. The html;
<h2>Contact Us</h2>
<br />
<table>
<tr>
<td style="align-items:center">
Name:</td>
<td>
<asp:TextBox ID="txtName"
runat="server"
Columns="40"></asp:TextBox>
</td>
</tr>
<tr>
<td style="align-items:center">
email:</td>
<td>
<asp:TextBox ID="txtEmail"
runat="server"
Columns="40"></asp:TextBox>
</td>
</tr>
<!-- Message -->
<tr>
<td style="align-items:center">
What are you looking for?
</td>
<td>
<asp:TextBox ID="txtMessage"
runat="server"
Columns="40"
Rows="6"
TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td style="align-items:center">
What would you be willing to pay for this app?</td>
<td>
<asp:TextBox ID="txtPay"
runat="server"
Columns="40"></asp:TextBox>
</td>
</tr>
<!-- Submit -->
<tr style="align-items:center">
<td colspan="2">
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" /><br />
</td>
</tr>
<!-- Results -->
<tr style="align-items:center">
<td colspan="2">
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td>
</tr>
</table>
This is the code behind page;
protected void btnSubmit_Click(object sender, EventArgs e)
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
try
{
//Create the msg object to be sent
MailMessage msg = new MailMessage();
//Add your email address to the recipients
msg.To.Add("[email protected]");
//Configure the address we are sending the mail from
msg.From = new MailAddress("info@MyWebsiteDomainName", "MyWeb Site");
msg.To.Add(new MailAddress("[email protected]"));
//Append their name in the beginning of the subject
msg.Subject = txtName.Text + txtEmail;
msg.Body = txtMessage.Text;
//Send the msg
smtpClient.Send(msg);
//Display some feedback to the user to let them know it was sent
lblResult.Text = "Your message was sent!";
//Clear the form
txtName.Text = "";
txtMessage.Text = "";
txtEmail.Text = "";
txtPay.Text = "";
lblResult.Text = "";
}
catch
{
//If the message failed at some point, let the user know
lblResult.Text = "Your message failed to send, please try again.";
}
}
Upvotes: 0
Views: 445
Reputation: 13960
Change this:
msg.From = new MailAddress("info@MyWebsiteDomainName", "MyWeb Site");
To:
msg.From = new MailAddress(txtEmail.Text, "MyWeb Site");
Upvotes: 1