Хотя уже есть несколько ответов, я подумал, что предлагаю немного альтернативный подход, используя Array.prototype.map()
, завернутый в функцию, которая может быть адаптирована пользователем (для обновления значения n
в символе nth
и измените используемый символ замены):
// defining the named function, with an 'opts' argument:
function replaceNthWith(opts) {
// setting the default options:
var defaults = {
// defining the nth character, in this case
// every fourth:
'nth': 4,
// defining the character to replace that
// nth character with:
'char': '|'
};
// Note that there's no default string argument,
// so that one argument must be provided in the
// opts object.
// iterating over each property in the
// opts Object:
for (var property in opts) {
// if the current property is a property of
// this Object, not inherited from the Object
// prototype:
if (opts.hasOwnProperty(property)) {
// we set that property of the defaults
// Object to be equal to that property
// as set in the opts Object:
defaults[property] = opts[property];
}
}
// if there is a defaults.string property
// (inherited from the opts.string property)
// then we go ahead; otherwise nothing happens
// note: this property must be set for the
// function to do anything useful:
if (defaults.string) {
// here we split the string supplied from the user,
// via opts.string, in defaults.string to form an
// Array of characters; we iterate over that Array
// with Array.prototype.map(), which process one
// Array and returns a new Array according to the
// anonymous function supplied:
return haystack = defaults.string.split('').map(function(character, index) {
// here, when the index of the current letter in the
// Array formed by Array.prototype.split() plus 1
// (JavaScript is zero-based) divided by the number
// held in defaults.nth is equal to zero - ensuring
// that the current letter is the 'nth' index we return
// the defaults.char character; otherwise we return
// the original character from the Array over which
// we're iterating:
return (index + 1) % parseInt(defaults.nth) === 0 ? defaults.char : character;
// here we join the Array back into a String, using
// Array.prototype.join() with an empty string:
}).join('');
}
}
// 'snippet.log()' is used only in this demonstration, in real life use
// 'console.log()', or print to screen or display in whatever other
// method you prefer:
snippet.log( replaceNthWith({ 'string': "abcdefoihewfojias" }) );
function replaceNthWith(opts) {
var defaults = {
'nth': 4,
'char': '|'
};
for (var property in opts) {
if (opts.hasOwnProperty(property)) {
defaults[property] = opts[property];
}
}
if (defaults.string) {
return haystack = defaults.string.split('').map(function(character, index) {
return (index + 1) % parseInt(defaults.nth) === 0 ? defaults.char : character;
}).join('');
}
}
// 'snippet.log()' is used only in this demonstration, in real life use
// 'console.log()', or print to screen or display in whatever other
// method you prefer.
// calling the function, passing in the supplied 'string'
// property value:
snippet.log( replaceNthWith({
'string': "abcdefoihewfojias"
}) );
// outputs: abc|efo|hew|oji|s
// calling the function with the same string, but to replace
// every second character ( 'nth' : 2 ):
snippet.log( replaceNthWith({
'string': "abcdefoihewfojias",
'nth': 2
}) );
// outputs: a|c|e|o|h|w|o|i|s
// passing in the same string once again, working on every
// third character, and replacing with a caret ('^'):
snippet.log( replaceNthWith({
'string': "abcdefoihewfojias",
'nth': 3,
'char' : '^'
}) );
// outputs: ab^de^oi^ew^oj^as
Ссылки:
Согласно документации MSDN , MailFormat теперь устарел. Предупреждение должно выглядеть так:
Предупреждение
Этот API теперь устарел. Рекомендуемая альтернатива: System.Net.Mail.
blockquote>Я бы предложил использовать свойство
MailMessage.AlternateViews
, чтобы предоставить HTML и текстовую альтернативу дляMailMessage
.Подробнее о MailMessage.AlternateViews . Согласно документации AlternateViews:
Используйте свойство AlternateViews, чтобы указать копии сообщения электронной почты в разных форматах. Например, если вы отправляете сообщение в формате HTML, вам также может потребоваться предоставить текстовую версию на случай, если некоторые из получателей используют программы чтения электронной почты, которые не могут отображать содержимое HTML. Пример, демонстрирующий создание сообщения с альтернативными представлениями, см. В AlternateViews.
blockquote>Ваш измененный код выглядит следующим образом:
public static string SendMail(string strsender, string strReceiver, string strsubject, string strbody) { try { MailMessage vMailMessage = new MailMessage(); char[] separator = { ',' }; vMailMessage.From = GetEmailAddress(strsender.Trim(), separator); //寄件人 //存取被拒 vMailMessage.To.Add(GetEmailAddress(strReceiver.Trim(), separator)); //收件人 //vMailMessage.Cc = GetEmailAddress(vDataRow["CC"].ToString().Trim(), separator); //副本 //vMailMessage.Bcc = GetEmailAddress(vDataRow["BCC"].ToString().Trim(), separator); //密件副本 vMailMessage.Subject = strsubject.Trim(); //主旨 vMailMessage.IsBodyHtml = true; vMailMessage.Body = strbody; SmtpMail.SmtpServer = "Webmail"; //設定Mail伺服器 SmtpMail.Send(vMailMessage); //發送mail return "ok"; } catch (Exception ex) { throw new Exception(ex.Message); } }