1

How does one store a statement in C# such as the following way

string EmailBody = "Request no.- ('" + objUserModel.ID + "') has been raised for special 
                            vehicle by requester-( '" + RequesterInfo + "'). " + 
                            "ORG_Unit:'"+ objUserModel.OrgUnit + "'" +
                            "TDC:'"+ objUserModel.TDC + "'" +
                            "Customer Name:'"+ objUserModel.CustName + "'" +
                            "Supply Plant:'"+ objUserModel.CustName + "'";

I am trying to show this variable in multilines in the email for that I need to store it in multiline in the string.

I have seen variations of @$"" but it is not working for me.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
sandeep pradhan
  • 261
  • 2
  • 8
  • 23
  • Is the email going to be plain text or HTML? – phuzi Feb 22 '22 at 16:04
  • Email body can be interpreted as HTML. You can add `
    ` each time you want a new line.
    – Xavier Brassoud Feb 22 '22 at 16:06
  • @phuzi email is going to be plain text – sandeep pradhan Feb 22 '22 at 16:08
  • @Xavier Could you give a code example for that – sandeep pradhan Feb 22 '22 at 16:08
  • `"Supply Plant:'"+ objUserModel.CustName + "'";` - perhaps a typo to use CustName here – Caius Jard Feb 22 '22 at 16:14
  • 1
    Email bodies can't be treated as HTML without actually generating an HTML body and specifying the correct headers. If your question is `How can I send well-formatted multiline emails` the answer would be `Use MailKit and create an HTML message` [as shown here](https://stackoverflow.com/questions/41160536/how-to-send-html-message-via-mimekit-mailkit) – Panagiotis Kanavos Feb 22 '22 at 16:15
  • *but it is not working for me* - to use `@$` you need to be on C# >= 8.0, by the way. `$@` is older – Caius Jard Feb 22 '22 at 16:18
  • What C# version are you using? And what does `not working` mean? If you use a multiline string in an HTML email, the newlines will be removed. In HTML, any whitespace is eliminated and replaced by a single space *unless* you use either the `
    ` tag. That's why HTML pages have `
    ` and `
    `s instead of newlines
    – Panagiotis Kanavos Feb 22 '22 at 16:52

6 Answers6

4

Take a look at interpolated strings for including your field values.

For the new lines, there are three distinct items to be aware of: the Enivronment.NewLine constant, the \n character literal, and the HTML <br> element. The last is especially important for emails which use an HTML body.

In this case, I suggest a C# mult-line string literal, with an interpolated value for an extra end line you can set or not as needed based on the platform.

So you end up with this:

string br = ""; // set this to "<br>" for HTML emails

string EmailBody = 
$@"Request no.- ('{objUserModel.ID}') has been raised for special{br}
vehicle by requester-( '{RequesterInfo}').{br}
{br}
ORG_Unit:'{objUserModel.OrgUnit}'{br}
TDC:'{objUserModel.TDC}'{br}
Customer Name:'{objUserModel.CustName}'{br}
Supply Plant:'{objUserModel.CustName}'";

The original code was having trouble because of the concatenation. Each line of code for the string was broken up at the end like this: " +, to continue again with a new string literal on the next line. In this way, the line breaks in the code were lost in the resulting string.

The code here addresses this issue by putting everything into the same string literal. There is only one set of double quotes defining the entire string, which now includes the line breaks built into the code. The one thing to be aware of with this technique is you want to shift your strings all the way to the left, regardless of any other indentation in the code.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
2

You can create a multiline string using a verbatim string, ie one starting with @. $ is used for string interpolation on both normal and verbatim strings. BUT that doesn't mean they'll appear as you expect in an email body.

Answering your specific question, this will create a multiline string:

    string EmailBody = $@"Request no.- ('{objUserModel.ID}') has been raised for special 
                        vehicle by requester-'({RequesterInfo}'). 
                        ORG_Unit:'{objUserModel.OrgUnit}'
                        TDC:'{objUserModel.TDC}'
                        Customer Name:'{objUserModel.CustName }'
                        Supply Plant:'{objUserModel.CustName}'";

Printing this produces:

Request no.- ('3') has been raised for special 
                            vehicle by requester-'(123456'). 
                            ORG_Unit:'Blah'
                            TDC:'XYZ'
                            Customer Name:'Gone'
                            Supply Plant:'Gone'

All tabs and spaces were included in the string. To avoid this, each line should start without indenting:

        string EmailBody = @$"Request no.- ('{objUserModel.ID}') has been raised for special 
vehicle by requester-'({RequesterInfo}'). 
ORG_Unit:'{objUserModel.OrgUnit}'
TDC:'{objUserModel.TDC}'
Customer Name:'{objUserModel.CustName }'
Supply Plant:'{objUserModel.CustName}'";

This produces:

Request no.- ('3') has been raised for special 
vehicle by requester-'(123456'). 
ORG_Unit:'Blah'
TDC:'XYZ'
Customer Name:'Gone'
Supply Plant:'Gone'

The order of the operators isn't significant. @$ behaves the same as $@.

Sending well formatted Emails

That's a different question, whose answer starts with Don't Use .NET's SmtpClient. The documentation page of the class warns :

We don't recommend that you use the SmtpClient class for new development because SmtpClient doesn't support many modern protocols. Use MailKit or other libraries instead. For more information, see SmtpClient shouldn't be used on GitHub.

The code needed to send a message with MailKit is similar to the old SmptClient.

using (var client = new SmtpClient ()) 
{
    await client.ConnectAsync("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);
    await client.AuthenticateAsync("username", "password");
    await client.SendAsync(message);

    await client.DisconnectAsync(true);
}

The Create Messages page shows how to create plain text or HTML messages. Some older email clients don't support HTML so it's often necessary to create both a plain text and HTML message.

String interpolation and verbatim strings can be used to create the text for both parts:

string plainBody = @$"Request no.- ('{objUserModel.ID}') has been raised for special 
vehicle by requester-'({RequesterInfo}'). 
ORG_Unit:'{objUserModel.OrgUnit}'
TDC:'{objUserModel.TDC}'
Customer Name:'{objUserModel.CustName }'
Supply Plant:'{objUserModel.CustName}'";

string htmlBody = @$"<div>Request no.- ('{objUserModel.ID}') has been raised for special 
vehicle by requester-'({RequesterInfo}').
</div>
<dl>
    <dt>ORG_Unit:</dt><dd>'{objUserModel.OrgUnit}'</dd>
    <dt>TDC:</dt><dd>'{objUserModel.TDC}'</dd?
    <dt>Customer Name:</dt><dd>'{objUserModel.CustName }'</dd?
    <dt>Supply Plant:</dt><dd>'{objUserModel.CustName}'</dd>
</dl>";

These can be combined in a single email message with :

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Blah Blah", "blah@gmail.com"));

message.Subject = "Special Request";

var builder = new BodyBuilder ();
builder.TextBody = plainBody;
builder.HtmlBody = htmlBody;

message.Body = builder.ToMessageBody ();
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
2

I suggest joining lines with required delimiter, e.g.

// Set "<br/>" if you want HTML delimiter  
// Put "\n" to have a new line, 
// Use Environment.NewLine to have OS specific delimiter
string delimiter = "<br/>";

string EmailBody = string.Join(delimiter,
  $"Request no.- ('{objUserModel.ID}') has been raised for special vehicle by requester-( '{RequesterInfo}'). ",
  $"ORG_Unit:'{objUserModel.OrgUnit}'",
  $"TDC:'{objUserModel.TDC}'",
  $"Customer Name:'{objUserModel.CustName}'",
  $"Supply Plant:'{objUserModel.CustName}'"
);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
-1

Try to use + Environment.NewLine where you need the newline.

GetGeeky
  • 39
  • 5
-1
+ "vehicle by requester - ('" + RequesterInfo + "'). " + "\n" + "ORG_Unit:'" + objUserModel.OrgUnit + "'" + "\n"
+ "TDC:'" + objUserModel.TDC + "'" + "\n" + "Customer Name:'" + objUserModel.CustName + "'" + "\n"
+ "Supply Plant:'" + objUserModel.CustName + "'";```

If i have understood it correctly you just add ```+ "\n" +```
br0mmie
  • 47
  • 9
-1

using string interpolation you can achieve what you want to do here for example:

string EmailBody = $"Request no.- ('\"{objUserModel.ID}\"') has been raised 

notice the \ before the "

if you would like to add a new line in the string you can just add string1 $" this string is writen on one line"; string2 $" this string is \nwriten on two lines";

Palisar
  • 69
  • 1
  • 5